[% setvar title Apocalypse 12: Objects %]
<div id="archive-notice">
    <h3>This file is part of the Perl 6 Archive</h3>
    <p>To see what is currently happening visit <a href="http://www.perl6.org/">http://www.perl6.org/</a></p>
</div>
<div class='pod'>
<pre>=encoding utf8</pre>
<a name='TITLE'></a><h1>TITLE</h1>
<p>Apocalypse 12: Objects</p>
<a name='AUTHOR'></a><h1>AUTHOR</h1>
<p>Larry Wall &lt;<a href='mailto:larry@wall.org'>larry@wall.org</a>&gt;</p>
<a name='VERSION'></a><h1>VERSION</h1>
<pre>  Maintainer: Larry Wall &lt;<a href='mailto:larry@wall.org'>larry@wall.org</a>&gt;
  Date: 13 Apr 2004
  Last Modified: 25 May 2006
  Number: 12
  Version: 8</pre>
<p>The official unofficial slogan of Perl 6 is &quot;Second System Syndrome
Done Right!&quot;.  After you read this Apocalypse you will at least be
certain that we got the &quot;Second System&quot; part down pat.  But we've
also put in a little bit of work on the &quot;Done Right&quot; part, which
we hope you'll recognize.  The management of complexity is complex,
but only if you think about it.  The goal of Perl 6 is to discourage
you from thinking about it unnecessarily.</p>
<p>Speaking of thinking unnecessarily, please don't think that everything
we write here is absolutely true.  We expect some things to change
as people point out various difficulties.  That's the way all the other
Apocalypses have worked, so why should this one be different?</p>
<p>When I say &quot;we&quot;, I don't just mean &quot;me&quot;.  I mean everyone who has
participated in the design, including the Perl 6 cabal, er, design team,
the readers (and writers) of the perl6-language mailing list, and all
the participants who wrote or commented on the original RFCs.  For this
Apocalypse we've directly considered the following RFCs:</p>
<pre>    RFC  PSA  Title
    ===  ===  =====
    032  abb  A method of allowing foreign objects in perl
    067  abb  Deep Copying, aka, cloning around.
    092  abb  Extensible Meta-Object Protocol
    095  acc  Object Classes
    101  bcc  Apache-like Event and Dispatch Handlers
    126  aaa  Ensuring Perl's object-oriented future
    137  bdd  Overview: Perl OO should I&lt;not&gt; be fundamentally changed.
    147  rr   Split Scalars and Objects/References into Two Types
    152  bdd  Replace invocant in @_ with self() builtin
    163  bdd  Objects: Autoaccessors for object data structures
    171  rr   my Dog $spot should call a constructor implicitly
    174  bdd  Improved parsing and flexibility of indirect object syntax
    187  abb  Objects : Mandatory and enhanced second argument to C&lt;bless&gt;
    188  acc  Objects : Private keys and methods
    189  abb  Objects : Hierarchical calls to initializers and destructors
    190  acc  Objects : NEXT pseudoclass for method redispatch
    193  acc  Objects : Core support for method delegation
    223  bdd  Objects: C&lt;use invocant&gt; pragma
    224  bdd  Objects : Rationalizing C&lt;ref&gt;, C&lt;attribute::reftype&gt;, and
		C&lt;builtin:blessed&gt;
    244  cdr  Method calls should not suffer from the action on a distance
    254  abb  Class Collections: Provide the ability to overload classes
    256  abb  Objects : Native support for multimethods
    265  abc  Interface polymorphism considered lovely
    277  bbb  Method calls SHOULD suffer from ambiguity by default
    307  rr   PRAYER - what gets said when you C&lt;bless&gt; something
    335  acc  Class Methods Introspection: what methods does this object
		support?
    336  bbb  use strict 'objects': a new pragma for using Java-like
		objects in Perl</pre>
<p>These RFCs contain many interesting ideas, and many more &quot;cries
for help&quot;.  Usually in these Apocalypses, I discuss the design with
respect to each of the RFCs.  However, in this case I won't, because
most of these RFCs fail in exactly the same way--they assume the Perl
6 object model to be a set of extensions to the Perl 5 object model.
But as it turns out, that would have been a great way to end up
with Second System Syndrome Done Wrong.  Perl 5's OO system is a
great workbench, but it has some issues that have to be dealt with
systematically rather than piecemeal.</p>
<a name='Some of the Problems with Perl 5 OO'></a><h2>Some of the Problems with Perl 5 OO</h2>
<a name='A little too orthogonal'></a><h3>A little too orthogonal</h3>
<p>It has often been claimed that Perl 5 OO was &quot;bolted on&quot;, but that's
inaccurate.  It was &quot;bolted through&quot;, at right angles to all other
reference types, such that any reference could be blessed into being
an object.  That's way cool, but it's often a little <i>too</i> cool.</p>
<a name='Not quite orthogonal enough'></a><h3>Not quite orthogonal enough</h3>
<p>It's too hard to treat built-in types as objects when you want to.
Perl 5's <code>tie</code> interface helps, but is suboptimal in several ways,
not the least of which is that it only works on variables, not values.</p>
<a name='Forced non-encapsulation'></a><h3>Forced non-encapsulation</h3>
<p>Because of the ability to turn (almost) anything into an object, a
derived class had to be aware of the internal data type of its base
class.  Even after convention settled on hashes as the appropriate
default data structure, one had to be careful not to stomp on the
attributes of one's base class.</p>
<a name='A little too minimal'></a><h3>A little too minimal</h3>
<p>Some people will be surprised to hear it, but Perl is a minimalist
language at heart.  It's just minimalistic about weird things
compared to your average language.  Just as the binding of parameters
to <code>@_</code> was a minimalistic approach, so too the entire Perl 5 object
system was an attempt to see how far you could drive a few features.
But many of the following difficulties stem from that.</p>
<a name='Too much keyword reuse'></a><h3>Too much keyword reuse</h3>
<p>In Perl 5, a class is just a package, a method is just a subroutine,
and an object is just a blessed referent.  That's all well and good,
and it is still fundamentally true in Perl 6.  However, Perl 5 made
the mistake of reusing the same keywords to express similar ideas.
That's not how natural languages work--we often use different words
to express similar ideas, the better to make subtle distinctions.</p>
<a name='Too difficult to capture metadata'></a><h3>Too difficult to capture metadata</h3>
<p>Because Perl 5 reused keywords and treated parameter binding as
something you do via a list assignment at run-time, it was next to
impossible for the compiler to tell which subroutines were methods
and which ones were really just subroutines.  Because hashes are
mutable, it was difficult to tell at compile time what the attribute
names were going to be.</p>
<a name='Inside-out interfaces'></a><h3>Inside-out interfaces</h3>
<p>The Perl 5 solution to the previous problem was to declare more
things at compile time.  Unfortunately, since the main way to do
things at compile time was to invoke <code>use</code>, all the compile-time
interfaces were shoehorned into <code>use</code>'s syntax, which, powerful
though it may be, is often completely inside-out from a reasonable
interface.  For instance, overloading is done by passing a list of
pairs to <code>use</code>, when it would be much more natural to simply declare
appropriate methods with appropriate names and traits.  The <code>base</code>
and <code>fields</code> pragmas are also kludges.</p>
<a name='Not enough convention'></a><h3>Not enough convention</h3>
<p>Because of the flexibility of the Perl 5 approach, there was never any
&quot;obvious&quot; way to do it.  So best practices had to be developed by each
group, and of course everyone came up with a slightly different solution.
Now, we're not going to be like some folks and confuse &quot;obvious&quot; with &quot;the
only way to do it&quot;.  This is still Perl, after all, and the flexibility
will still be there if you need it.  But by convention, there needs to
be a standard look to objects and classes so that they can interoperate.
There's more than one way to do it, but one of those is the standard way.</p>
<a name='Wrong conventions'></a><h3>Wrong conventions</h3>
<p>The use of arrow where most of the rest of the world uses dot was confusing.</p>
<a name='Everything possible, but difficult'></a><h3>Everything possible, but difficult</h3>
<p>The upshot of the previous problems was that, while Perl 5 made it
easy to <i>use</i> objects and classes, it was difficult to try to define
classes or derive from them.</p>
<a name='Perl 5 Non-Problems'></a><h2>Perl 5 Non-Problems</h2>
<p>While there are plenty of problems with Perl 5's OO system, there are some
things it did right.</p>
<a name='Generating class by running code at compile time'></a><h3>Generating class by running code at compile time</h3>
<p>One of the big advances in Perl 5 was that a program could be in charge
of its own compilation via <code>use</code> statements and <code>BEGIN</code> blocks.
A Perl program isn't a passive thing that a compiler has its way with,
willy nilly.  It's an active thing that negotiates with the compiler
for a set of semantics.  In Perl 6 we're not shying away from that,
but taking it further, and at the same time hiding it in a more
declarative style.  So you need to be aware that, although many of
the things we'll be talking about here <i>look</i> like declarations, they
trigger Perl code that runs during compilation.  Of such methods are
metaclasses made.  (While these methods are often triggered by grammar
rule reductions, remember from Apocalypse 5 that all these grammar
rules are also running under the user's control.  You can tweak
the language without the crude ax of source filtering.)</p>
<a name='There are many roads to polymorphism'></a><h3>There are many roads to polymorphism</h3>
<p>In looking for an &quot;obvious&quot; way to conventionalize Perl's object
system, we shouldn't overlook the fact that there's more than one
obvious way, and different approaches work better in different
circumstances.  Inheritance is one way (and typically the most
overused), but we also need good support for composition,
delegation, and parametric types.  Cutting across those techniques
are issues of interface, implementation, and mixtures of interface
and implementation.  There are multiple strategies for ambiguity
resolution as well, and no single strategy is always right.  (Unless
the boss says so.)</p>
<a name='People using a class shouldn't have to think hard'></a><h3>People using a class shouldn't have to think hard</h3>
<p>In making it easier to define and derive classes, we must be careful not
to make it harder to <i>use</i> classes.</p>
<a name='Trust in Convention, but Keep Your Powder Dry'></a><h2>Trust in Convention, but Keep Your Powder Dry</h2>
<p>So to summarize this summary, what we're proposing to develop is a
set of conventions for how object orientation ought to work in Perl
6--by default.  But there should also be enough hooks to customize
things to your heart's content, hopefully without undue impact on the
sensibilities of others.</p>
<p>And in particular, there's enough flexibility in the new approach
that, if you want to, you can still program in a way much like the
old Perl 5 approach.  There's still a <code>bless</code> method, and you can
still pretend that an object is a hash--though it isn't anymore.</p>
<p>However, as with all the rest of the design of Perl 6, the overriding
concern has been that the language scale well.  That means Perl has
to scale down as well as up.  Perl has to work well both as a first
language and as a last language.  We believe our design fulfills
this goal--though, of course, only time will tell.</p>
<p>One other note: if you haven't read the previous Apocalypses and
Exegeses, a lot of this is going to be complete gobbledygook to you.
(Of course, even if you <i>have</i> read them, this might still be
gobbledygook.  You take your chances in life...)</p>
<a name='An Easy Example'></a><h1>An Easy Example</h1>
<p>Before we start talking about all the hard things that should be
possible, let's look at an example of some of the easy things that
should be easy.  Suppose we define a Point object that (for some
strange reason) allows you to adjust the y-axis but not the x-axis.</p>
<pre>    class Point {
	has $.x;
	has $.y is rw;

	method clear () { $.x = 0; $.y = 0; }
    }

    my $point = Point.new(x =&gt; 2, y =&gt; 3);

    $a = $point.y;	# okay
    $point.y = 42;	# okay

    $b = $point.x;	# okay
    $point.x = -1;	# illegal, default is read-only

    $point.clear;	# reset to 0,0</pre>
<p>If you compare that to how it would have to be written in Perl 5,
you'll note a number of differences:</p>
<ul>
<li><a name='It uses the keywords class and method rather than package and sub.'></a>It uses the keywords <code>class</code> and <code>method</code> rather than <code>package</code>
and <code>sub</code>.</li>
<li><a name='The attributes are named in explicit declarations rather than implicit hash keys.'></a>The attributes are named in explicit declarations rather than implicit
hash keys.</li>
<li><a name='It is impossible to confuse the attribute variables with ordinary variables because of the extra dot (which also associates the attributes visually with method calls).'></a>It is impossible to confuse the attribute variables with ordinary
variables because of the extra dot (which also associates the
attributes visually with method calls).</li>
<li><a name='Perhaps most importantly, we did not have to commit to using a hash (or any other external data structure) for the object's values.'></a>Perhaps most importantly, we did not have to commit to using a hash
(or any other external data structure) for the object's values.</li>
<li><a name='We didn't have to write a constructor.'></a>We didn't have to write a constructor.</li>
<li><a name='The implicit constructor automatically knows how to map named arguments to the attribute names.'></a>The implicit constructor automatically knows how to map named arguments
to the attribute names.</li>
<li><a name='We didn't have to write the accessor methods.'></a>We didn't have to write the accessor methods.</li>
<li><a name='The accessors are by default read-only outside the class, and you can't get at the attributes from outside the class without an accessor. (Inside the class you can use the attributes directly.)'></a>The accessors are by default read-only outside the class, and you
can't get at the attributes from outside the class without an accessor.
(Inside the class you can use the attributes directly.)</li>
<p>[Update: The &quot;<code>.</code>&quot; form of the attribute syntax is now construed to
always be a virtual dispatch to the accessor, so you can use that
syntax in any of the child classes too.  To refer to the private
storage you now use &quot;<code>!</code>&quot; in place of the &quot;<code>.</code>&quot;.  Within the lexical
scope of the class you may omit even that.]</p>
<li><a name='The invocant of the clear method is implicit.'></a>The invocant of the <code>clear</code> method is implicit.</li>
<li><a name='And perhaps most obviously, Perl 6 uses . instead of -&gt; to dereference an object.'></a>And perhaps most obviously, Perl 6 uses <code>.</code> instead of <code>-&gt;</code>
to dereference an object.</li>
</ul>
<p>Now suppose we want to derive from Point, and add a z-axis.  That's just</p>
<pre>    class Point3d is Point {
	has $:z = 123;
	method clear () { $:z = 0; next; }
    }
    my $point3d = Point3d.new(x =&gt; 2, y =&gt; 3, z =&gt; 4);
    $c = $point3d.z;	# illegal, $:z is invisible</pre>
<p>The implicit constructor automatically sorts out the named arguments
to the correct initializers for you.  If you omit the z value,
it will default to 123.  And the new <code>clear</code> method calls the old
clear method merely by invoking <code>next</code>, without the dodgy &quot;super&quot;
semantics that break down under MI.  We also declared the <code>$:z</code>
attribute to be completely private by using a colon instead of a dot.
No accessor for it is visible outside the class.  (And yes, OO purists,
our other attributes should probably have been private in the first
place...that's why we're making it just as easy to write a private
attribute as a public one.)</p>
<p>[Update: It's now <i>easier</i> to write a private attribute than a public
one.  We've change the <code>:</code> twigil to <code>!</code>, and made it optional,
so you can just declare it as <code>has $z</code>, or as <code>has $!z</code> if you wish
to emphasize the privateness of it.]</p>
<p>If any of that makes your head spin, I'm sure the following will clear
it right up.  <code>:-)</code></p>
<a name='Classes'></a><h1>Classes</h1>
<p>A class is what provides a name and a place for the abstract behavior
of a set of objects said to belong to the class.</p>
<p>As in Perl 5, a class is still &quot;just a funny package&quot;, structurally
speaking.  Syntactically, however, a class is now distinct from a
package or a module.  And the body of a class definition now runs in
the context of a metaclass, which is just a way of saying that it has
a metaclass instance as its (undeclared) invocant.  (An &quot;invocant&quot;
is what we call the object or class on behalf of which a method
is being called.)  Hence class definitions, though apparently
declarative, are also executing code to build the class definition,
and the various declarations within the class are also running bits
of code.  By convention classes will use a standard metaclass, but
that's just convention.  (A very strong convention, we hope.)</p>
<p>The primary role of a class is to manage instances, that is, objects.
So a class must worry about object creation and destruction, and
everything that happens in between.  Classes have a secondary
role as units of software reuse, in that they can be inherited
from or delegated to.  However, because this is a secondary role,
and because of weaknesses in models of inheritance, composition,
and delegation, Perl 6 will split out the notion of software reuse
into a separate class-like entity called a &quot;role&quot;.  Roles are an
abstraction mechanism for use by classes that don't care about
the secondary aspects of software reuse, or that (looking at it
the other way) care so much about it that they want to encapsulate
any decisions about implementation, composition, delegation, and
maybe even inheritance.  Sounds fancy, but just think of them as
includes of partial classes, with some safety checks.  Roles don't
manage objects.  They manage interfaces and other abstract behavior
(like default implementations), and they help classes manage objects.
As such, a role may only be composed into a class or into another role,
never inherited from or delegated to.  That's what classes are for.</p>
<p>[Update: In reality things are a little looser than that.  If you use
a role as if it were a class, it autoinstantiates an anonymous class
for you that just does that role.  If you use a class as if it were
a role, it takes a role-like snapshot of the current state of the class
and freezes it into an anonymous role.]</p>
<p>Classes are arranged in an inheritance hierarchy by their &quot;isa&quot;
relationships.  Perl 6 supports multiple inheritance, but makes it
easy to program in a single-inheritance style, insofar as roles make
it easy to mix in (or delegate, or parameterize) private implementation
details that don't belong in the public inheritance tree.</p>
<p>In those cases where MI is used, there can be ambiguities in the
pecking order of classes in different branches.  Perl 6 will have
a canonical way to disambiguate these, but by design the dispatch
policy is separable from inheritance, so that you can change the
rules for a given set of classes.  (Certainly the rules can change
when we call into another language's class hierarchy, for instance.)</p>
<p>Where possible, class names are treated polymorphically, just
as method names are.  This powerful feature makes it possible to
inherit systems of classes in parallel.  (These classes might be
inner classes, or they might be inner aliases to outer classes.)
By making the class names &quot;virtual&quot;, the base classes can refer to
the appropriate derived classes without knowing their full name.
That sounds complicated, but it just means that if you do the normal
thing, Perl will call the right class instead of the one you thought
it was going to call.  <code>:-)</code></p>
<p>(As in C++ culture, we use the term &quot;virtual&quot; to denote a method that
dispatched based on the actual run-time type of the object rather
than the declared type of the variable.  C++ classes have to declare
their methods to be virtual explicitly.  All of Perl's public methods
are virtual implicitly.)</p>
<p>You may derive from any built-in class.  For high-level object classes
such as <code>Int</code> or <code>Num</code> there are no restrictions on how you derive.
For low-level representational classes like <code>int</code> or <code>num</code>, you may
not change the representation of the value; you may only add behaviors.
(If you want to change the representation, you should probably be
using composition instead of inheritance.  Or define your own low-level
type.)  Apart from this, you don't need to worry about the difference
between <code>int</code> and <code>Int</code>, or <code>num</code> and <code>Num</code>, since Perl 6 will
do autoboxing.</p>
<a name='Declaration of Classes'></a><h2>Declaration of Classes</h2>
<p>Class declarations may be either file scoped or block scoped.
A file-scoped declaration must be the first thing in the file, and
looks like this:</p>
<pre>    class Dog is Mammal;
    has Limb @.paws;
    method walk () { .paws».move() }</pre>
<p>That has the advantage of avoiding the use of one set of braces,
letting you put everything up against left margin.  It is otherwise
identical to a block-scoped class, which looks like this:</p>
<pre>    class Dog is Mammal {
	has Limb @.paws;
	method walk () { .paws».move() }
    }</pre>
<p>[Update: That <code>.paws</code> would have to be write <code>@.paws</code> these days unless
you put the invocant into <code>$_</code>.]</p>
<p>An incomplete class definition makes use of the <code>...</code> (&quot;yada, yada,
yada&quot;) operator:</p>
<pre>    class Dog is Mammal {...}</pre>
<p>The declaration of a class name introduces the name as a valid
bare identifier or name.  In the absence of such a declaration, the
name of a class in an expression must be introduced with the <code>::</code>
class sigil, or it will be considered a bareword and rejected, since
Perl 6 doesn't allow barewords.  Once the name is declared however,
it may be used as an ordinary term in an expression.  Unlike in Perl
5, you should not view it as a bareword string.  Rather, you should
view it as a parameterless subroutine that returns a class object,
which conveniently stringifies to the name of the class for Perl
5 compatibility.  But when you say</p>
<pre>    Dog.new()</pre>
<p>the invocant of <code>new</code> is an object of type <code>Class</code>, not a string as
in Perl 5.</p>
<p>[Update: There is no <code>Class</code> class now.  The <code>Dog</code> object is of
type <code>Dog</code>, the same type as any of its instances.  It's just not
a real <code>Dog</code>.  It's an abstract <code>Dog</code>.]</p>
<p>Unmodified, a class declaration always declares a global name.
But if you prefix it with <code>our</code>, you're defining an inner class:</p>
<pre>    class Cell {
	our class Golgi {...}
	...
    }</pre>
<p>The full name of the inner class is <code>Cell::Golgi</code>, and that name can
be used outside of <code>Cell</code>, since <code>Golgi</code> is declared in the <code>Cell</code> package.
(Classes may be declared private, however.  More later.)</p>
<p>[Update: Bare class declarations now always default to <code>our</code>.  The top
level class ends up in the global space merely because files start out
being parsed in the <code>*</code> package (aka <code>GLOBAL::</code>), so that's where
the first class declaration puts its name.]</p>
<a name='Class traits'></a><h3>Class traits</h3>
<p>A class declaration may apply various traits to the class.  (A trait is
a property applied at compile time.)  When you apply a trait, you're
accepting whatever it is that that trait does to your class, which could
be pretty much anything.  Traits do things <i>to</i> classes.  Do not confuse
traits with roles, which are sworn to play a subservient role to the class.
Traits can do whatever they jolly well please to your class's metadata.</p>
<p>Now, the usual thing to do to a class's metadata is to insert another
class into its ISA metadata.  So we use trait notation to install
a superclass:</p>
<pre>    class Dog is Mammal {...}</pre>
<p>To specify multiple inheritance, just add another trait:</p>
<pre>    class Dog is Mammal is Pet {...}</pre>
<p>But often you'll want a role instead, specified with <code>does</code>:</p>
<pre>    class Dog is Mammal does Pet {...}</pre>
<p>More on that later.  But remember that traits are evil.  You can have
traits like:</p>
<pre>    class Moose is Mammal is stuffed is really(Hatrack) is spy(Russian) {...}</pre>
<p>So what if you actually want to derive from <code>stuffed</code>?  That's a good
question, which we will answer later.  (The short answer is, you don't.)</p>
<p>Now as it happens, you can also use <code>is</code> from within the class.
You can also put the <code>does</code> inside to include various roles:</p>
<pre>    class Dog {
	is Mammal;
	does Pet;
	does Servant;
	does Best::Friend[Man];
	does Drool;
	...
    }</pre>
<p>In fact, there's no particular reason to put any of these outside the
braces except to make them more obvious to the casual reader.  If we
take the view that inheritance is just one form of implementation,
then a simple</p>
<pre>    class Dog {...}</pre>
<p>is sufficient to establish that there's a <code>Dog</code> class defined out there
somewhere.  We shouldn't really care about the implementation of <code>Dog</code>,
only its interface--which is usually pretty slobbery.</p>
<p>That being said, you can know more about the interface at compile
time once you know the inheritance, so it's good to have pulled in
a definition of the class as well as a declaration.  Since this
is typically done with <code>use</code>, the inheritance tree is generally
available even if you don't mark your class declaration externally
with the inheritance.  (But in any event, the actual inheritance tree
doesn't have to be available till run time, since that's when methods
are dispatched.  (Though as is often the case, certain optimizations
work better when you give them more data earlier...))</p>
<a name='Use of Classes'></a><h2>Use of Classes</h2>
<p>A class is used directly by calling class methods, and indirectly by
calling methods of an object of that class (or of a derived class that
doesn't override the methods in question).</p>
<p>Classes may also be used as objects in their own right, as instances
of a metaclass, the class <code>MetaClass</code> by default.  When you declare
class <code>Dog</code>, you're actually calling a metaclass class method that
constructs a metaclass instance (i.e. the <code>Dog</code> class) and then
calls the associated closure (i.e the body of the class) as a method
on the instance.  (With a little grammatical magic thrown in so that
<code>Dog</code> isn't considered a bareword.)</p>
<p>The class <code>Dog</code> is an instance of the class <code>MetaClass</code>, but it's
also an instance of the type <code>Class</code> when you're thinking of
it as a dispatcher.  That is, a class object is really allomorphic.
If you treat one as an instance of Class, it behaves as if it were
the user's view of the class, and the user thinks the class is there only to
dispatch to the user's own class and instance methods.  If, however,
you treat the object as an instance of <code>MetaClass</code>, you get access
to all its metaclass methods rather than the user-defined methods.
Another way to look at it is that the metaclass object is a separate object
that manages the class object.  In any event, you can get from the ordinary
class object to its corresponding metaclass object via the <code>.meta</code>
method, which every object supports.</p>
<p>[Update: Every <code>Dog</code> object (class or instance) just points to its
metaclass instance.  The <code>Dog</code> class object isn't either a <code>Class</code>
or a <code>MetaClass</code> object.  Perhaps it does a <code>Class</code> role though.]</p>
<p>By the way, a <code>Class</code> is a <code>Module</code> which in turn is a <code>Package</code> which in
turn is an <code>Object</code>.  Or something like that.  So a class can always
be used as if it were a mere module or package.  But modules and packages
don't have a <code>.dispatch</code> method...</p>
<p>[Update: The preceding paragraph is really only true if you take it
as talking about the metaclasses, not the classes.  A <code>Dog</code> is not
a <code>Module</code>.  <code>Dog.meta</code> is a metaclass instance that can do modular
and package operations as well as class operations, and all these
metaobjects use packages as their global storage.  That is, the
metaclass &quot;does&quot; the Package interface, on some level or other, if
it wants to make global names visible through the package interface.]</p>
<p>By default, classes in Perl are left open.  That is, you can add
more methods later.  (However, an application may close them.)
For discussion of this, see the section on &quot;Open vs Closed Classes&quot;.</p>
<a name='Class Name Semantics'></a><h1>Class Name Semantics</h1>
<p>Class names (and module names) are just package names.</p>
<p>Unlike in Perl 5, when you mention a package name in Perl 6 it doesn't
always mean a global name, since Perl 6 knows about inner classes
and lexically scoped packages and such.  As with other entities in Perl
such as variables and methods, a scan is made for who thinks they have
the best definition of the name, going out from lexical scopes to package
scope to global scope in the case of static class names, and via method
inheritance rules in the case of virtual class names.</p>
<p>Note that <code>::MyClass</code> and <code>MyClass</code> mean the same thing.  In Perl
6, an initial <code>::</code> is merely an optional sigil for when the name of
the package would be misconstrued as something else.  It specifically
does not mean (as it does in Perl 5) that it is a top-level package.
To refer to the top-level package, you would need to say something
like <code>::*MyClass</code> (or just <code>*MyClass</code> in places where the <code>*</code>
unary operator would not be expected.)  But also note that the <code>*</code>
package in Perl is not the &quot;<code>main</code>&quot; package in the Perl 5 sense.</p>
<p>Likewise, the presence of <code>::</code> within a package name like
<code>Fish::Carp</code> does not make it a global package name necessarily.
Again, it scans out through various scopes, and only if no local
scopes define package <code>Fish::Carp</code> do you get the global definition.
And again, you can force it by saying <code>::*Fish::Carp</code>.  (Or just
<code>*Fish::Carp</code> in places where the <code>*</code> unary operator is not expected.)
<code>GLOBAL::Fish::Carp</code> means the same thing.</p>
<p>You can interpolate a parenthesized expression within a package name
after any <code>::</code>.  So these are all legal package names (or module
names, or class names):</p>
<pre>    ::($alice)
    ::($alice)::($bob)
    ::($alice::($bob))
    ::*::($alice)::Bob
    ::('*')::($alice ~ '_misc')::Bob
    ::(get_my_dir())
    ::(@multilevel)</pre>
<p>And any of those package names could be part of a variable or sub name:</p>
<pre>    $::($alice)::name
    @::($alice)::($bob)::elems[1,2,3]
    %::*::($alice)::Bob::map{'xyz'}
    &amp;::('*')::($alice ~ '_misc')::Bob::doit(1,2,3)
    $::(get_my_dir())::x
    $::(@multilevel)</pre>
<p>Note in the last example that the final element of <code>@multilevel</code>
is taken to be the variable name.  This may be illegal under <code>use
strict refs</code>, since it amounts to a symbolic reference.  (Not that the
others aren't symbolic, but the rules may be looser for package names
than for variable names, depending on how strict our strictures get.)</p>
<p>[Update: There is no &quot;strict refs&quot; anymore, since we have a separate
syntax for when we explicitly want symbolic references.]</p>
<a name='Private Classes'></a><h2>Private Classes</h2>
<p>A class named with a single initial colon is a private class name:</p>
<pre>    class :MyPrivateClass {...}</pre>
<p>It is completely ignored outside of the current class.  Since the name
is useful only in the current package, it makes no sense to try to
qualify it with a package name.  While it's an inner class of sorts,
it does not override any class name from any other class because it
lives in its own namespace (a subnamespace of the current package),
and there's no way to tell if the class you're deriving from declares
its own private class of the same name (apart from digging through
the reflection interfaces).</p>
<p>The colon is orthogonal to the scoping.  What's actually going on in
this example is that the name is stored in the package with the leading
colon, because the colon is part of the name.  But if you declared
&quot;<code>my class :Golgi</code>&quot; the private name would go into the lexical
namespace with the colon.  The colon functions a bit like a &quot;private&quot;
trait, but isn't really a trait.  Wherever you might use a private
name, the colon in the name effectively creates a private subspace
of names, just as if you'd prefixed it with &quot;_&quot; in the good old days.</p>
<p>But if were only that, it would just be encapsulation by convention.
We're trying to do a little better than that.  So the language needs
to actively prevent people from accessing that private subspace from
outside the class.  You might think that that's going to slow down
all the dispatchers, but probably not.  The ordinary dispatch of
<code>Class.method</code> and <code>$obj.method</code> don't have to worry about it,
because they use bare identifiers.  It's only when people start
doing <code>::($class)</code> or <code>$obj.$method</code> that we have to trap illegal
references to colonic names.</p>
<p>Even though the initial colon isn't really a trait, if you interrogate the
&quot;<code>.private</code>&quot; property of the class, it will return true.  You don't have
to parse the name to get that info.</p>
<p>We'll make more of this when we talk about private methods and
attributes.  Speaking of methods...</p>
<p>[Update: Private attributes are now marked with <code>!</code> rather than <code>:</code>,
but nowadays you should just use a lexically scoped class if you want
a private class.]</p>
<a name='Methods'></a><h1>Methods</h1>
<p>Methods are the actions that a class knows how to invoke on behalf of
an object of that type (or on behalf of itself, as a class object).
But you knew that already.</p>
<p>As in Perl 5, a method is still &quot;just a funny subroutine&quot;, but in
Perl 6 we use a different keyword to declare it, both because it's
better documentation, and because it captures the metadata for the
class at compile time.  Ordinary methods may be declared only within
the scope of a class definition.  (Multimethods are exempt from this
restriction, however.)</p>
<a name='Declaration of Methods'></a><h2>Declaration of Methods</h2>
<p>To declare a method, use the <code>method</code> keyword just as you would
use <code>sub</code> for an ordinary subroutine.  The declaration is otherwise
almost identical:</p>
<pre>    method doit ($a, $b, $c) { ... }</pre>
<p>The one other difference is that a method has an <i>invocant</i> on
behalf of which the method is called.  In the declaration above, that
invocant is implicit.  (It is implicitly typed to be the same as the
current surrounding class definition.)  You may, however, explicitly
declare the invocant as the first argument.  The declaration knows
you're doing that because you put a colon between the invocant and
the rest of the arguments:</p>
<pre>    method doit ($self: $a, $b, $c) { ... }</pre>
<p>In this case, we didn't specify the type of <code>$self</code>, so it's an
untyped variable.  To make the exact equivalent of the implicit
declaration, put the current class:</p>
<pre>    method doit (MyClass $self: $a, $b, $c) { ... }</pre>
<p>or more generically using the <code>::_</code> &quot;current class&quot; pronoun:</p>
<pre>    method doit (::_ $self: $a, $b, $c) { ... }</pre>
<p>[Update: The current lexical class is now named via <code>::?CLASS</code>.
To capture the actual class of the invocant, use a type variable
like <code>::RealClass</code> in the declaration, with or without the <code>$self</code>.]</p>
<p>In any case, the method sets the current invocant as the topic, which is
also known as the <code>$_</code> variable.  However, the topic can change depending
on the code inside the method.  So you might want to declare an explicit
invocant when the meaning of <code>$_</code> might change.  (For further discussion
of topics see Apocalypse 4.  For a small writeup on sub signatures see
Apocalypse 6.)</p>
<p>[Update: Methods do not set the topic now unless you declare the invocant
with the name <code>$_</code>.]</p>
<p>A private method is declared with a colon on the front:</p>
<pre>    method :think (Brain $self: $thought)</pre>
<p>Private methods are callable only by the class itself, and by trusted
&quot;friends&quot;.  More about that when we talk about attributes.</p>
<p>[Update: Private methods are marked with <code>!</code> now rather than <code>:</code>.]</p>
<a name='Use of Methods'></a><h2>Use of Methods</h2>
<p>As in Perl 5, there are two notations for calling ordinary methods.
They are called the &quot;dot&quot; notation and the &quot;indirect object&quot; notation.</p>
<a name='The dot notation'></a><h3>The dot notation</h3>
<p>Perl 6's &quot;dot&quot; notation is just the industry-standard way to call
a method these days.  (This used to be <code>-&gt;</code> in Perl 5.)</p>
<pre>    $object.doit(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;);</pre>
<p>If the object in question is the current topic, <code>$_</code>, then you can use
the unary form of the dot operator:</p>
<pre>    for @objects {
	.doit(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;);
    }</pre>
<p>A simple variable may be used for an indirectly named method:</p>
<pre>    my $dosomething = &quot;doit&quot;;
    $object.$dosomething(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;);</pre>
<p>As in Perl 5, if you want to do anything fancier, use a temporary variable.</p>
<p>The parentheses may also be omitted when the following code is unambiguously
a term or operator, so you can write things like this:</p>
<pre>    @thumbs.each { .twiddle }	# same as @thumbs.each({.twiddle})
    $thumb.twiddle + 1		# same as $thumb.twiddle() + 1
    .mode 1			# same as $_.mode(1)</pre>
<p>[Update: This is retracted.  Parens are always required if there are
arguments.]</p>
<p>[Update: As an alternative to parens, you can turn any otherwise legal
method call into a list operator by appending a <code>:</code>.]</p>
<p>(Parens are always required around the argument list when a method call
with arguments is interpolated into a string.)</p>
<p>The parser <i>will</i> make use of whitespace at this point to decide some things.
For instance</p>
<pre>    $obj.method + 1</pre>
<p>is obviously a method with no arguments, while</p>
<pre>    $obj.method +1</pre>
<p>is obviously a method with an argument.  However, the dwimmery only goes
as far as the typical person's visual intuition.  Any construct too ambiguous
is simply rejected.  So</p>
<pre>    $obj.method+1</pre>
<p>produces a parse error.</p>
<p>[Update: The preceding is also retracted.  None of those would be
interpreted as arguments now.  However, most of the following is still true.]</p>
<p>In particular, curlies, brackets, or parens would be interpreted
as postfix subscripts or argument lists if you leave out the space.
In other words, Perl 6 distinguishes:</p>
<pre>    $obj.method ($x + $y) + $z	# means $obj.method(($x + $y) + $z)</pre>
<p>[Update: That's illegal now.]</p>
<p>from</p>
<pre>    $obj.method($x + $y) + $z   # means ($obj.method($x + $y)) + $z</pre>
<p>Yes, this is different from Perl 5.  And yes, I know certain people
hate it.  They can write their own grammar.</p>
<p>While it's always possible to disambiguate with parentheses, sometimes
that is just too unsightly.  Many methods want to be parsed as if
they were list operators.  So as an alternative to parenthesizing
the entire argument list, you can disambiguate by putting a colon
between the method call and the argument list:</p>
<pre>    @thumbs.each: { .twiddle }	# same as @thumbs.each({.twiddle})
    $thumb.twiddle: + 1		# same as $thumb.twiddle(+ 1)
    .mode: 1			# same as $_.mode(1)
    $obj.for: 1,2,3 -&gt; $i { ... }</pre>
<p>[Update: There is no colon disambiguator any more.  Use parens if there
are arguments.  (However, you can pass an adverbial block using <code>:{}</code>
notation with a null key.  That does not count as an ordinary argument.)]</p>
<p>[Update: The colon disambiguator is back again.  The problem with
precedence is now solved by requiring that a bare closure in the list
is always interpreted as the final argument unless followed by a comma
or comma surrogate.]</p>
<p>If a method is declared with the trait &quot;<code>is rw</code>&quot;, it's an lvalue
method, and you can assign to it just as if it were an ordinary
variable:</p>
<pre>    method mystate is rw () { return $:secretstate }

    $object.mystate = 42;
    print $object.mystate;	# prints 42</pre>
<p>In fact, it's a general rule that you can use an argumentless &quot;<code>rw</code>&quot; method
call anywhere you might use a variable:</p>
<pre>    temp $state.pi = 3;
    $tailref = \$fido.tail;</pre>
<p>(Though occasionally you might need to supply parentheses to
disambiguate, since the compiler can't always know at compile time
whether the method has any arguments.)</p>
<p>[Update: The parens (or a colon) are required if there are arguments.]</p>
<p>Method calls on container objects are obviously directed to the
container object itself, not to the contents of the container:</p>
<pre>    $elems = @array.elems;
    @keys  = %hash.keys;
    $sig   = &amp;sub.signature;</pre>
<p>However, with scalar variables, methods are always directed to the
object pointed to by the reference contained in the scalar:</p>
<pre>    $scalar = @array;		# (implied \ in scalar context)
    $elems = $scalar.elems;	# returns @array.elems</pre>
<p>or for value types, the appropriate class is called as if the value
were a reference to a &quot;real&quot; object.</p>
<pre>    $scalar = &quot;foo&quot;;
    $chars = $scalar.chars;	# calls Str::chars or some such</pre>
<p>In order to talk to the scalar container itself, use the <code>tied()</code>
pseudo-function as you would in Perl 5:</p>
<pre>    if tied($scalar).constant {...}</pre>
<p>(You may recall, however, that in Perl 6 it's illegal to tie any
variable without first declaring it as tieable, or (preferably) tying
it directly in the variable's declaration.  Otherwise the optimizer
would have to assume that every variable has semantics that are
unknowable in advance, and we would have to call it a pessimizer
rather than an optimizer.)</p>
<p>[Update: The function is now called <code>variable()</code> instead of tied()
to avoid that confusion.]</p>
<a name='The &quot;indirect object&quot; notation'></a><h3>The &quot;indirect object&quot; notation</h3>
<p>The other form of method call is known as the &quot;indirect object&quot; syntax,
although it differs from Perl 5's syntax in that a colon is required
between the indirect object (the invocant) and its arguments:</p>
<pre>    doit $object: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;</pre>
<p>The colon may be omitted if there are no arguments (besides the invocant):</p>
<pre>    twiddle $thumb;
    $x = new X;</pre>
<p>Note that indirect object calls may not be directly interpolated into
a string, since they don't start with a sigil.  You can always use the
<code>$()</code> expression interpolater though:</p>
<pre>    say &quot;$(greet $lang), world!&quot;;</pre>
<p>[Update: The <code>$()</code> notation means something else now.  Use</p>
<pre>    say &quot;{greet $lang}, world!&quot;;</pre>
<p>instead.]</p>
<p>As in Perl 5, the indirect object syntax is valid only if you haven't
declared a subroutine locally that overrides the method lookup.
That was a bit of a problem in Perl 5 since, if there happened to be
a <code>new</code> constructor in your class, it would call that instead
dispatching to the class you wanted it to.  That's much less of a
problem in Perl 6, however, because Perl 6 cannot confuse a method
declaration with a subroutine declaration.  (Which is yet another reason
for giving methods their own keyword.)</p>
<p>Another factor that makes indirect objects work better in Perl 6
is that the class name in &quot;<code>new X</code>&quot; is a predeclared object, not a
bare identifier.  (Perl 5 just had to guess when it saw two bare
identifiers in a row that you were trying to call a class method.)</p>
<p>The indirect object syntax may not be used with a variable for the
methodname.  You must use dot notation for that.</p>
<p>Because of precedence, the indirect object notation may not be used
as an lvalue unless you parenthesize it:</p>
<pre>    (mystate $object) = 42;
    (findtail Dog: &quot;fido&quot;) = Wagging::on;</pre>
<p>You may parenthesize an argumentless indirect object method to make
it look like a function:</p>
<pre>    mystate($object) = 42;
    twiddle($thumb);</pre>
<p>The dispatch rules for methods and global multi subs conspire to keep
these unambiguous, so the user really doesn't have to worry about whether</p>
<pre>    close($handle);</pre>
<p>is implemented as a global multi sub or a method on a <code>$handle</code> object.
In essence, the multimethod dispatching rules degenerate to ordinary
method dispatch when there are no extra arguments to consider (and
sometimes even when there are arguments).  This is particularly important
because Perl uses these rules to tell the difference between</p>
<pre>    print &quot;Howdy, world!\n&quot;;	# global multi sub</pre>
<p>and</p>
<pre>    print $*OUT;		# ordinary filehandle method</pre>
<p>However, you must still put the colon after the invocant if there are
other arguments.  The colon tells the parser whether to look for the
arguments inside:</p>
<pre>    doit($object: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;)</pre>
<p>or outside:</p>
<pre>    doit($object): &quot;a&quot;, &quot;b&quot;, &quot;c&quot;</pre>
<p>If you do say</p>
<pre>    doit($object, &quot;a&quot;, &quot;b&quot;, &quot;c&quot;)</pre>
<p>the first comma forces it to be interpreted as a sub call rather than
a method call.</p>
<p>(We could have decided to say that whenever Perl can't find a <code>doit()</code>
sub definition at run time, it should assume you meant the entire
parenthesized list to be the indirect object, which, since it's in
scalar context would automatically generate a list reference and call
<code>[$object,&quot;a&quot;,&quot;b&quot;,&quot;c&quot;].doit()</code>, which is unlikely to be what
you mean, or even work.  (Unless, of course, that's how you really
meant it to work.)  But I think it's much more straightforward to
simply disallow comma lists at the top level of an indirect object.
The old &quot;if it looks like a function&quot; rule applies here.  Oddly,
though, function syntax is how you call multisubs in Perl 6.  And as
it happens, the way the multisub/multimethod dispatch rules are
defined, it could still end up calling <code>$object.doit(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)</code>
if that is deemed to be the best choice among all the candidates.
But syntactically, it's not an indirect object.  More on dispatch
rule interactions later.)</p>
<p>The comma still doesn't work if you go the other way and leave out
the parens entirely, since</p>
<pre>    doit $object, &quot;a&quot;, &quot;b&quot;, &quot;c&quot;;</pre>
<p>would always (in the absence of a prior sub declaration) be parsed as</p>
<pre>    (doit $object:), &quot;a&quot;, &quot;b&quot;, &quot;c&quot;;</pre>
<p>So a print with both an indirect object and arguments has to look
like one of these:</p>
<pre>    print $*OUT: &quot;Howdy, world!\n&quot;;
    print($*OUT: &quot;Howdy, world!\n&quot;);
    print($*OUT): &quot;Howdy, world!\n&quot;;</pre>
<p>Note that the old Perl 5 form using curlies:</p>
<pre>    print {some_hairy_expression()} &quot;Howdy, world!\n&quot;;</pre>
<p>should instead now be written with parentheses:</p>
<pre>    print (some_hairy_expression()): &quot;Howdy, world!\n&quot;;</pre>
<p>though, in fact, in this case the parens are unnecessary:</p>
<pre>    print some_hairy_expression(): &quot;Howdy, world!\n&quot;;</pre>
<p>You'd only need the parens if the invocant expression contained
operators lower in precedence than comma (comma itself not being
allowed).  Basically, if it looks confusing to you, you can expect
it to look confusing to the compiler, and to make the compiler look
confused.  But it's a feature for the compiler to look confused when
it actually <i>is</i> confused.  (In Perl 5 this was not always so.)</p>
<p>Note that the disambiguating colon associates with the closest method
call, whether direct or indirect.  So</p>
<pre>    print $obj.meth: &quot;Howdy, world!\n&quot;;</pre>
<p>passes &quot;<code>Howdy, world!\n</code>&quot; to <code>$obj.meth</code> rather than to <code>print</code>.
That's a case where you ought to have parenthesized the indirect object
for clarity anyway:</p>
<pre>    print ($obj.meth): &quot;Howdy, world!\n&quot;;</pre>
<a name='Calling private methods'></a><h3>Calling private methods</h3>
<p>A private method does not participate in normal method dispatch.
It is not listed in the class's public methods.  The <code>.can</code> method
does not see it.  Calling it via normal dispatch raises a &quot;no such
method&quot; exception.  It is, in essence, invisible to the
outside world.  It does not hide a base class's method of the same
name--even in the current class!  It's fair to ask for warnings about
name collisions, of course.  But we're not following the C++ approach
of making private methods visible but uncallable, because that would
violate encapsulation, and in particular, <a href='http://en.wikipedia.org/wiki/Liskov_substitution_principle.' target='_blank'>en.wikipedia.org</a>
Instead, we separate the namespaces completely by distinguishing the
public dot operator from the private dot-colon operator.  That is:</p>
<pre>    $mouth.say(&quot;Yes!&quot;)		# always calls public .say method
          .say(&quot;Yes!&quot;)		# unary form
    $brain.:think(&quot;No!&quot;)	# always calls private :think method
          .:think(&quot;No!&quot;)	# unary form</pre>
<p>[Update: We now use <code>!</code> instead of <code>.:</code> and there is no unary form.]</p>
<p>The inclusion of the colon prevents any kind of &quot;virtual&quot; behavior.
Calling a private method is illegal except under two very specific
conditions.  You can call a private method <code>:think</code> on an object
<code>$brain</code> only if:</p>
<ul>
<li><a name='1.'></a>1.</li>
<p>The class of <code>$brain</code> is explicitly declared, and the declared class
is either the class definition that we are in or a class that has
explicitly granted trust to our current class, and the declared
class contains a private <code>:think</code> method.  Or...</p>
<li><a name='2.'></a>2.</li>
<p>The class of the <code>$brain</code> is not declared, and the current class contains
a private <code>:think</code> method.</p>
</ul>
<p>The upshot of these rules is that a private method call is essentially
a subroutine call with a method-like syntax.  But the private method
we're going to call can be determined at compile time, just like
a subroutine.</p>
<a name='Class Methods'></a><h1>Class Methods</h1>
<p>Class methods are called on the class as a whole rather than on any
particular instance object of the class.  They are distinguished
from ordinary methods only by the declared type of the invocant.
Since an implicit invocant would be typed as an object of the class
and not as the class itself, the invocant declaration is <i>not</i>
optional in a class method declaration if you wish to specify the
type of the invocant.  (Untyped explicit invocants are allowed to
&quot;squint&quot;, however.)</p>
<p>[Update: Squinting is no longer necessary now that we've defined class
objects to merely be uninstantiated prototypes of the same type as the
instances in the class.]</p>
<a name='Class Invocant'></a><h2>Class Invocant</h2>
<p>To declare an ordinary class method, such as a constructor, you say
something like:</p>
<pre>    method new (Class $class: *@args) { ... }</pre>
<p>Such a method may only be called with an invocant that &quot;isa&quot; <code>Class</code>,
that is, an object of type <code>Class</code>, or derived from type <code>Class</code>.</p>
<p>[Update: No Class class exists.]</p>
<a name='Class|object Invocant'></a><h2>Class|object Invocant</h2>
<p>It is possible to write a method that can be called with an invocant that
is either a <code>Class</code> or an object of that current class.  You can declare the
method with a type junction:</p>
<pre>    method new (Class|Dog $classorobj: *@args) { ... }</pre>
<p>Or to be completely non-specific, you can leave out the type entirely:</p>
<pre>    method new ($something: *@args) { ... }</pre>
<p>That's not as dangerous as it looks, since almost by definition
the dispatcher only calls methods that are consistent with the
inheritance tree.  You just can't say:</p>
<pre>    method new (*@args) { ... }</pre>
<p>which would be the equivalent of</p>
<pre>    method new (Dog $_: *@args) { ... }</pre>
<p>Well, actually, you <i>could</i> say that, but it would require that
you have an existing <code>Dog</code>-compatible object in order to create a new one.
And that could present a little bootstrapping problem...</p>
<p>[Update: We simply made <code>Dog</code> a <code>Dog</code>-compatible object.]</p>
<p>(Though it could certainly cure the boot chewing problem...)</p>
<p>But in fact, you'll rarely need to declare <code>new</code> method at all,
because Perl supplies a default constructor to go with your class.</p>
<a name='Submethods'></a><h1>Submethods</h1>
<p>Some methods are intended to be inherited by derived classes.  Others
are intended to be reimplemented in every class, or in every class
that doesn't want the default method.  We call these &quot;submethods&quot;,
because they work a little like subs, and a little like methods.
(You can also read the &quot;sub&quot; with the meaning it has in words like
&quot;subhuman&quot;.)</p>
<p>Typically these are (sub)methods related to the details of construction
and destruction of the object.  So when you call a constructor, for
instance, it ends up calling the <code>BUILDALL</code> initialization routine for
the class, which ends up calling the <code>BUILD</code> submethod:</p>
<pre>    submethod BUILD ($a, $b, $c) {
	$.a = $a;
	$.b = $b;
	$.c = $c;
    }</pre>
<p>Since the submethod is doing things that make sense only in the
context of the current class (such as initializing attributes), it
makes no sense for <code>BUILD</code> to be inherited.  Likewise <code>DESTROY</code>
is also a submethod.</p>
<p>Why not just make them ordinary subs, then?  Ordinary subs can't
be called by method invocation, and we want to call these routines
that way.  Furthermore, if your base class <i>does</i> define an ordinary
method named <code>BUILD</code> or <code>DESTROY</code>, it can serve as the default
<code>BUILD</code> or <code>DESTROY</code> for all derived classes that don't declare
their own submethods.  (All public methods are virtual in Perl,
but some are more virtual than others.)</p>
<p>You might be saying to yourself, &quot;Wait, private methods aren't virtual.
Why not just use a private method for this?&quot;  It's true that private
methods aren't virtual, because they aren't in fact methods at all.
They're just ordinary subroutines in disguise.  They have nothing to
do with inheritance.  By contrast, submethods are all about presenting
a unified inherited <i>interface</i> with the option of either inheriting or
not inheriting the <i>implementation</i> of that interface, at the discretion
of the class doing the implementing.</p>
<p>So the bottom line is that submethods allow you to override an
inherited implementation for the current class without overriding
the default implementation for other classes.  But in any case, it's
still using a public interface, called as an ordinary method call,
from anywhere in your program that has an object of your type.</p>
<p>Or a class of your type.  The default <code>new</code> constructor is an ordinary
class method in class <code>Object</code>, so it's inherited by all classes that
don't define their own <code>new</code>.  But when you write your own <code>new</code>,
you need to decide whether your constructor should be inherited or not.
If so, that's good, and you should declare it as a method.  But if
not, you should declare it as a submethod so that derived classes
don't try to use it erroneously instead of the default <code>Object.new()</code>.</p>
<a name='Attributes'></a><h1>Attributes</h1>
<p>In Perl 6, &quot;attributes&quot; are what we call the instance variables of
an object.  (We used that word to mean something else in Perl 5--we're
now calling those things &quot;traits&quot; or &quot;properties&quot;.)</p>
<p>As with classes and methods, attribute declarations are apparently
declarative.  Underneath they actually call a method in the metaclass
to install the new definition.  The Perl 6 implementation of attributes
is not based on a hash, but on something more like a symbol table.
Attributes are stored in an opaque datatype rather like a struct in
C, or an array in Perl 5--but you don't know that.  The datatype is
opaque in the sense that you shouldn't care how it's laid out in memory
(unless you have to interface with an outside data structure--like a
C struct).  Do not confuse opacity with encapsulation.  Encapsulation
only hides the object's implementation from the outside world.  But
the object's structure is opaque even to the class that defines it.</p>
<p>One of the large benefits of this is that you can actually take a C or
C++ data structure and wrap accessor methods around it without having
to copy anything into a different data structure.  This should speed
up things like XML parsing.</p>
<a name='Declaration of Attributes'></a><h2>Declaration of Attributes</h2>
<p>In order to provide this opaque abstraction layer, attributes are
not declared as a part of any other data structure.  Instead, they
are modeled on real variables, whose storage details are implicitly
delegated to the scope in which they are declared.  So attributes
are declared as if they were normal variables, but with a strange
scope and lifetime that is neither <code>my</code> nor <code>our</code>.  (That scope is,
of course, the current object, and the variable lives as long as the
object lasts.)  The class will implicitly store those attributes in a
location distinct from any other class's attributes of the same name,
including any base or derived class.  To declare an attribute variable,
declare it within the class definition as you would a <code>my</code> variable,
but use the <code>has</code> declarator instead of <code>my</code>:</p>
<pre>    class Dog is Mammal {
	has $.tail;
	has @.legs;
	...
    }</pre>
<p>The <code>has</code> declarator was chosen to remind people that attributes are
in a &quot;HASA&quot; relationship to the object rather than an &quot;ISA&quot; relationship.</p>
<p>The other difference from normal variables is that attributes have a
secondary sigil that indicates that they are associated with methods.
When you declare an attribute like <code>$.tail</code>, you're also implicitly
declaring an accessor method of the same name, only without the <code>$</code> on
the front.  The dot is there to remind you that it's also a method call.</p>
<p>As with other declarations, you may add various traits to an attribute:</p>
<pre>    has $.dogtag is rw;</pre>
<p>If you want all your attributes to default to &quot;<code>rw</code>&quot;, you can put the
attribute on the class itself:</p>
<pre>    class Coordinates is rw {
	has int $.x;
	has int $.y;
	has int $.z;
    }</pre>
<p>Essentially, it's now a C-style struct, without having to introduce
an ugly word like &quot;struct&quot; into the language.  Take that, C++.  <code>:-)</code></p>
<p>You can also assign to a declaration:</p>
<pre>    has $.master = &quot;TheDamian&quot;;</pre>
<p>Well, actually, this looks like an assignment, but it isn't.
The effect of this is to establish a default; it is not executed at
run time.  (Or more precisely, it runs when the class closure is
executed by the metaclass, so it gets evaluated only once and the
value is stored for later use by real instances.  More below.)</p>
<a name='Use of Attributes'></a><h2>Use of Attributes</h2>
<p>The attribute behaves just like an ordinary variable within the
class's instance methods.  You can read and write the attributes just
like ordinary variables.  (It is, however, illegal to refer to an
instance attribute variable (that is, a &quot;<code>has</code>&quot; variable) from within
a class method.  Class methods may only access class attributes,
not instance attributes.  See below.)</p>
<p>[Update: Class methods are no longer distinguished from instance
methods by the compiler, except insofar as the compiler can tell that a
method refers to instance variables in the body.  It's a run-time error
to ask for an attribute of a class object, but that's because the class
object doesn't have the attribute, not because it's a class object.]</p>
<p>Bare attributes are automatically hidden from the outside world because
their sigiled names cannot be seen outside the class's package.
This is how Perl 6 enforces encapsulation.  Outside the class the
<i>only</i> way to talk about an attribute is through accessor methods.
Since public methods are always virtual in Perl, this makes attribute
access virtual outside the class.  Always.  (Unless you give the
optimizer enough hints to optimize the class to &quot;final&quot;.  More on
that later.)</p>
<p>In other words, only the class itself is allowed to know whether this
attribute is, in fact, implemented by this class.  The class may also
choose to ignore that fact, and call the abstract interface, that is,
the accessor method, in which case it might actually end up calling
some derived class's overriding method, which might in turn call
back to this class's accessor as a super method.  (So in general,
an accessor method should always refer to its actual variable name
rather than the accessor method name to avoid infinite recursion.)</p>
<p>[Update: All public $.foo variables are now virtual, and the actual
private storage is represented by $!foo.]</p>
<p>You may write your own accessor methods around the bare attributes,
but if you don't, Perl will generate them for you based on the
declaration of the attribute variable.  The traits of the generated
method correspond directly to the traits on the variable.</p>
<p>By default, a generated accessor is read-only (because by default any
method is read-only).  If you mark an attribute with the trait
&quot;<code>is rw</code>&quot; though, the corresponding generated accessor will also be
marked &quot;<code>is rw</code>&quot;, meaning that it can be used as an lvalue.</p>
<p>In any event, even without &quot;<code>is rw</code>&quot; the attribute variable is always
writable within the class itself (unless you apply the trait <code>is
constant</code> to it).</p>
<p>As with private classes and methods, attributes are declared private
using a colon on the front of their names.  As with any private
method, a private accessor is completely ignored outside its class
(or, by extension, the classes trusted by this class).</p>
<p>To carry the separate namespace idea through, we incorporate the
colon as the secondary sigil in declarations of private attributes:</p>
<pre>    has $:x;</pre>
<p>Then we can get rid of the verbose <code>is private</code> altogether.  Well,
it's still there as a trait, but the colon implies it, and is required
anyway.)  And we basically force people to document the private/public
distinction every place they reference <code>$:x</code> instead of <code>$.x</code>,
or <code>$obj.:meth</code> instead of <code>$obj.meth</code>.</p>
<p>We've seen secondary sigils before in earlier Apocalypses.  In each case
they're associated with a bizarre usage of some sort.  So far we
have:</p>
<pre>    $*foo	# a truly global global (in every package)
    $?foo	# a regex-scoped variable
    $^foo	# an autodeclared parameter variable
    $.foo	# a public attribute
    $:foo	# a private attribute</pre>
<p>[Update: A regex-scoped variable now looks like <code>$&lt;foo&gt;</code> instead.
A <code>$?foo</code> variable is now a compiler variable, and a <code>$=foo</code>
variable is a POD variable.  A private attribute is <code>$!foo</code>.
By the way, lately we've been calling the secondary sigils &quot;twigils&quot;.]</p>
<p>As a form of the dreaded &quot;Hungarian notation&quot;, secondary sigils are
not introduced lightly.  We define secondary sigils only where we
deem instant recognizability to be crucial for readability.  Just as
you should never have to look at a variable and guess whether it's
a true global, you should never have to look at a method and guess
which variables are attributes and which ones are variables you just
happen to be in the lexical scope of.  Or which attributes are public
and which are private.  In Perl 6 it's always obvious--at the cost
of a secondary sigil.</p>
<p>We do hereby solemnly swear to never, never, ever add tertiary sigils.
You have been warned.</p>
<a name='Default Values'></a><h2>Default Values</h2>
<p>You can set default values on attributes by pseudo-assignment to
the attribute declaration:</p>
<pre>    has Answer $.ans = 42;</pre>
<p>These default values are associated as &quot;<code>build</code>&quot; traits of the attribute
declaration object.  When the <code>BUILD</code> submethod is initializing a new
object, these prototype values are used for uninitialized attributes.
The expression on the right is evaluated immediately at the point of
declaration, but you can defer evaluation by passing a closure, which
will automatically be evaluated at the actual initialization time.
(Therefore, to initialize to a closure value, you have to put a closure
in a closure.)</p>
<p>Here's the difference between those three approaches.  Suppose you say:</p>
<pre>    class Hitchhiker {
	my $defaultanswer = 0;
	has $.ans1 = $defaultanswer;
	has $.ans2 = { $defaultanswer };
	has $.ans3 = { { $defaultanswer } };
	$defaultanswer = 42;
	...
    }</pre>
<p>When the object is eventually constructed, <code>$.ans1</code> will be
initialized to <code>0</code>, while <code>$.ans2</code> will be initialized to 42.
(That's because the closure binds <code>$defaultanswer</code> to the current
variable, which still presumably has the value 42 by the time the <code>BUILD</code>
routine initializes the new object, even though the lexical variable
&quot;<code>$defaultanswer</code>&quot; has supposedly gone out of scope by the time the
object is being constructed.  That's just how closures work.)</p>
<p>And <code>$.ans3</code> will be initialized not to 42, but to a closure that,
if you ever call it, will also return 42.  So since the accessor
<code>$obj.ans3()</code> returns that closure, <code>$obj.ans3().()</code> will return 42.</p>
<p>The default value is actually stored under the &quot;<code>build</code>&quot; trait, so this:</p>
<pre>    has $.x = calc($y);</pre>
<p>is equivalent to this:</p>
<pre>    has $.x is build( calc($y) );</pre>
<p>and this:</p>
<pre>    has $.x = { calc($y) };</pre>
<p>is equivalent to either of these:</p>
<pre>    has $.x is build( { calc($y) } );
    has $.x will build { calc($y) };</pre>
<p>As with all closure-valued container traits, the container being
declared (the <code>$.x</code> variable in this case) is passed as the topic to
the closure (in addition to being the target that will be initialized
with the result of the closure, because that's what <code>build</code> does).
In addition to the magical topic, these build traits are also magically
passed the same named arguments that are passed to the <code>BUILD</code> routine.
So you could say</p>
<pre>    has $.x = { calc($^y) };</pre>
<p>to do a calculation based on the <code>:y(582)</code> parameter originally passed to
the constructor.  Or rather, that will be passed to the constructor
someday when the object is eventually constructed.  Remember we're
really still at class construction time here.</p>
<p>As with other initializers, you can be more specific about the time
at which the default value is constructed, as long as that time is
earlier than class construction time:</p>
<pre>    has $.x = BEGIN { calc() }
    has $.x = CHECK { calc() }
    has $.x = INIT  { calc() }
    has $.x = FIRST { calc() }
    has $.x = ENTER { calc() }</pre>
<p>which are really just short for:</p>
<pre>    has $.x is build( BEGIN { calc() } )
    has $.x is build( CHECK { calc() } )
    has $.x is build( INIT  { calc() } )
    has $.x is build( FIRST { calc() } )
    has $.x is build( ENTER { calc() } )</pre>
<a name='Class Attributes'></a><h1>Class Attributes</h1>
<p>In general, class attributes are just package or lexical variables.
If you define a package variable with a dot or colon, it autogenerates
an accessor for you just as it does for an ordinary attribute:</p>
<pre>    our $.count;	# generates a public read-only .count accessor
    our %:cache is rw;	# generates a private read-write .:cache accessor</pre>
<p>The implicit invocant of these implicit accessors has a &quot;squinting&quot;
type--it can either be the class or an object of the class.  (Declare
your own accessors if you have a philosophical reason for forcing
the type one way or the other.)</p>
<p>[Update: Squinting no longer necessary.]</p>
<p>The disadvantage of using &quot;<code>our</code>&quot; above is that that both of these are
accessible from outside the class via their package name (though the
private one is Officially Ignored, and cannot be named simply by saying
<code>%MyClass:::cache</code> because that syntax is specifically disallowed).</p>
<p>If on the other hand you declare your class variables lexically:</p>
<pre>    my $.count;		# generates a read-only .count accessor
    my %:cache is rw;	# generates a read-write .:cache accessor</pre>
<p>then the same pair of accessors are generated, but the variables
themselves are visible only within the class block.  If you reopen
the class in another block, you can only see the accessors, not the
bare variables.  This is probably a feature.</p>
<p>Generally speaking, though, unless you want to provide public
accessors for your class attributes, it's best to just declare
them as ordinary variables (either <code>my</code> or <code>state</code> variables)
to prevent confusion with instance attributes.  It's a good policy
not to declare any public accessors until you know you need them.
They are, after all, part of your contract with the outside world,
and the outside world has a way of holding you to your contracts.</p>
<a name='Object Construction'></a><h1>Object Construction</h1>
<p>The basic idea here is to remove the drudgery of creating objects.
In addition we want object creation and cleanup to work right by
default.  In Perl 5 it's possible to make recursive construction and
destruction work, but it's not the default, and it's not easy.</p>
<p>Perl 5 also confused the notions of constructor and initializer.
A constructor should create a new object once, then call all the
appropriate initializers in the inheritance tree without recreating
the object.  The initializer for a base class should be called before
the initializer for any class derived from it.</p>
<p>The initializer for a class is always named <code>BUILD</code>.  It's in uppercase
because it's usually called automatically for you at construction time.</p>
<p>As with Perl 5, a constructor is only named &quot;<code>new</code>&quot; by convention,
and you can write a constructor with any name you like.  However,
in Perl 6, if you do not supply a &quot;<code>new</code>&quot; method, a generic one will
be provided (by inheritance from <code>Object</code>, as it happens).</p>
<a name='The Default Constructor'></a><h2>The Default Constructor</h2>
<p>The default <code>new</code> constructor looks like this:</p>
<pre>    multi method new (Class $class: *%_) {
	return $class.bless(0, *%_);
    }</pre>
<p>[Update: Now that we have parametric types it's more like:</p>
<pre>    method new (::T: *%_) {
	return T.bless(*%_);
    }</pre>
<p>That binds the class type of the invocant regardless of how instantiated
the invocant is.  Also, the candidate argument need not be supplied.]</p>
<p>The arguments for the default constructor are always named arguments,
hence the <code>*%_</code> declaration to collect all those pairs and pass them
on to bless.</p>
<p>You'll note also that <code>bless</code> is no longer a subroutine but a
method call, so it's now impossible to omit the class specification.
This makes it easier to inherit constructors. You can still bless
any reference you could bless in Perl 5, but where you previously
used a function to do that:</p>
<pre>    # Perl 5 code...
    return bless( {attr =&gt; &quot;hi&quot;}, $class );</pre>
<p>in Perl 6 you use a method call:</p>
<pre>    # Perl 6 code...
    return $class.bless( {attr =&gt; &quot;hi&quot;} );</pre>
<p>However, if what you pass as the first argument isn't a reference,
<code>bless</code> is going to construct an opaque object and initialize it.  In a
sense, <code>bless</code> is the only real constructor in Perl 6.  It first makes
sure the data structure is created.  If you don't supply a reference
to bless, it calls <code>CREATE</code> to create the object.  Then it calls
<code>BUILDALL</code> to call all the initializers.</p>
<p>The signature of <code>bless</code> is something like:</p>
<pre>    method bless ($class: $candidate, *%_)</pre>
<p>The <code>0</code> candidate indicates the built-in opaque type.  If you're really
strange in the head, you can think of the &quot;<code>0</code>&quot; as standing for
&quot;<code>0paque</code>&quot;.  Or it's the &quot;zero&quot; object, about which we know zip.
Whatever tilts your windmill...</p>
<p>In any event, strings are reserved for other object layouts.  We could
conceivably have things like:</p>
<pre>    return $class.bless(&quot;Cstruct&quot;, *%_);</pre>
<p>So as it happens, <code>0</code> is short for the layout &quot;P6opaque&quot;.</p>
<p>[Update: There is no <code>0</code> argument.  Just leave it out if you wish to
declare a <code>P6opaque</code> object.  If you wish to pass some other representation
name to <code>CREATE</code>, just call <code>CREATE</code> first and pass the result of that
as your candidate to <code>bless</code>,]</p>
<p>Any additional arguments to <code>.bless</code> are automatically passed on to
<code>CREATE</code> and <code>BUILDALL</code>.  But note that these <i>must</i> be named arguments.
It could be argued that the <i>only</i> real purpose for writing a <code>.new</code>
constructor in Perl 6 is to translate different positional argument
signatures into a unified set of named arguments.  Any other
initialization common to all constructors should be done within <code>BUILD</code>.</p>
<p>Oh, the invocant of <code>.bless</code> is either a class or an object of the
class, but if you use an object of the class, the contents of that
object are <i>not</i> automatically used to prototype the new object.
If you wish to do that, you have to do it explicitly by copying the
attributes:</p>
<pre>    $obj.bless(0, *%$obj)</pre>
<p>(That is just a specific application of the general principle that
if you treat any object like a hash, it will behave like one, to the
extent that it can.  That is, <code>%$obj</code> turns the attributes into key/value
pairs, and passes those as arguments to initialize the new object.
Note that <code>%$obj</code> includes the private attributes when used inside
the class, but not outside.)</p>
<p>[Update: These days the <code>*</code> would be replaced by a <code>[,]</code> reduction.]</p>
<p>Just because <code>.bless</code> allows an object to be used for a class doesn't
mean your <code>new</code> constructor has to do the same.  Some folks have
philosophical issues with mixing up classes and objects, and it's fine
to disallow that on the constructor level.  In fact, you'll note that
the default <code>.new</code> above requires a <code>Class</code> as its invocant.  Unless you
override it, it doesn't allow an object for the constructor invocant.
Go thou and don't likewise.</p>
<p>[Update: Sorry, the new <code>::T</code> parametric type syntax doesn't care
whether the invocant is a class or an object.  It does, however,
document that you're only interested in the type of the invocant.]</p>
<a name='The Default Cloner'></a><h3>The Default Cloner</h3>
<p>Another good reason not to overload <code>.new</code> to do cloning is that
Perl will also supply a default <code>.clone</code> routine that works something
like this:</p>
<pre>    multi method clone ($proto: *%_) {
	return $proto.bless(0, *%_, *%$proto);
    }</pre>
<p>Note the order of the two hash arguments to <code>bless</code>. This gives the
supplied attribute values precedence over the copied attribute
values, so that you can change some of the attributes <i>en passant</i>
if you like. That's because we're passing the two flattened hashes
as arguments to <code>.bless</code> and Perl 6's named argument binding mechanism
always picks the <i>first</i> argument that matches, not the last. This
is opposite of what happens when you use the Perl 5 idiom:</p>
<pre>    %newvals = (%_, %$proto);</pre>
<p>In that case, the <i>last</i> value (the one in %$proto) would &quot;win&quot;.</p>
<p>[Update: We now do &quot;last wins&quot; semantics for named args, unless the
argument in question is declared as an array, in which case it gets
all the arguments of that name.]</p>
<a name='CREATE'></a><h2>CREATE</h2>
<pre>    submethod CREATE ($self: *%args) {...}</pre>
<p><code>CREATE</code> is called when you don't want to use an existing data structure
as the candidate for your object.  In general you won't define <code>CREATE</code>
because the default <code>CREATE</code> does all the heavy magic to bring an opaque
object into existence.  But if you don't want an opaque object, and you
don't care to write all your constructors to create the data structure
before calling <code>.bless</code>, you can define your own <code>CREATE</code> submethod, and
it will override the standard one for all constructors in the class.</p>
<p>[Update: The <code>$self</code> here should probably read <code>::T</code>.]</p>
<a name='BUILDALL'></a><h2>BUILDALL</h2>
<pre>    submethod BUILDALL ($self: *%args) {...}</pre>
<p>[Update: But this one actually <i>is</i> the new self, the candidate created
by <code>CREATE</code> above.  It's just not entirely instantiated until <code>BUILDALL</code> is
done.]</p>
<p>After the data structure is created, it must be populated by each
of the participating classes (and roles) in the proper order.
The <code>BUILDALL</code> method is called upon to do this.  The default
<code>BUILDALL</code> is usually correct, so you don't generally have to
override it.  In essence, it delegates the initialization of parent
classes to the <code>BUILDALL</code> of the parent classes, and then it calls
<code>BUILD</code> on the current class.  In this way the pieces of the object
are assembled in the correct order, from least derived to most derived.</p>
<p>For each class <code>BUILDALL</code> calls on, if the arguments contain a pair
whose key is that class name, it passes the value of the pair as
its argument to that class's <code>BUILDALL</code>.  Otherwise it passes
the entire list.  (There's not much ambiguity there--most classes
and roles will start with upper case, while most attribute names
start with lower case.)</p>
<a name='BUILD'></a><h2>BUILD</h2>
<pre>    submethod BUILD ($self: *%args) {...}</pre>
<p>That is the generic signature of <code>BUILD</code> from the viewpoint of the
caller, but the typical <code>BUILD</code> routine declares explicit parameters
named after the attributes:</p>
<pre>    submethod BUILD (+$tail, +@legs, *%extraargs) {
	$.tail = $tail;
	@:legs = @legs;
	...
    }</pre>
<p>[Update: That would be <code>(:$tail, :@legs, *%extraargs)</code> now, but
you don't really need the colons since positional declarations
can still be set by name.]</p>
<p>That occurs so frequently that there's a shorthand available in the
signature declaration.  You can put the attributes (distinguished
by those secondary sigils, you'll recall) right into the signature.
The following means essentially the same thing, without repeating
the names:</p>
<pre>    submethod BUILD (+$.tail, +@:legs, *%extraargs) {...}</pre>
<p>[Update: <code>@!legs</code> now.  The <code>!</code> may not be omitted in this case.]</p>
<p>It's actually unnecessary to declare the <code>*%extraargs</code> parameter.
If you leave it out, it will default to <code>*%_</code> (but only on methods
and submethods--see the section on Interface Consistency later).</p>
<p>You may use this special syntax only for instance attributes, not class
attributes.  Class attributes should generally not be reinitialized
every time you make a new object, after all.</p>
<p>If you do not declare a <code>BUILD</code> routine, a default routine will be
supplied that initializes any attributes whose names correspond to
the keys of the argument pairs passed to it, and leaves the other
attributes to default to whatever the class supplied as the default,
or <code>undef</code> otherwise.</p>
<p>In any event, the assignment of default attribute values happens
automatically.  For any attribute that is not otherwise initialized,
the attribute declaration's &quot;<code>build</code>&quot; property is evaluated and the
resulting value copied in to the newly created attribute slot.
This happens logically at the end of the <code>BUILD</code> block, so we avoid
running initialization closures unnecessarily.  This implicit
initialization is based not on whether the attribute is undefined,
but on whether it was initialized earlier in <code>BUILD</code>.  (Otherwise we
could never explicitly create an attribute with an undefined value.)</p>
<a name='Eliminating Redundancy in Constructor Calls'></a><h2>Eliminating Redundancy in Constructor Calls</h2>
<p>If you say:</p>
<pre>    my Dog $spot = Dog.new(...)</pre>
<p>you have to repeat the type.  That's not a big deal for a small
typename, but sometime typenames are a lot longer.  Plus you'd like
to get rid of the redundancy, just because it's, like, redundant.
So there's a variant on the dot operator that looks a lot like a
dot assignment operator:</p>
<pre>    my Dog $spot .= new(...)</pre>
<p>It doesn't really quite fit the assignment operator rule though. If
it did, it'd have to mean</p>
<pre>    my Dog $spot = $spot.new(...)</pre>
<p>which doesn't quite work, because <code>$spot</code> is undefined.  What probably
happens is that the <code>my</code> cheats and puts a version of <code>undef</code> in
there that knows it should dispatch to the <code>Dog</code> class if you call
<code>.self:new()</code> on it.  Anyway, we'll make it work one way or another,
so that it becomes the equivalent of:</p>
<pre>    my Dog $spot = Dog.new(...)</pre>
<p>The alternative is to go the C++ route and make <code>new</code> a reserved word.
We're just not gonna do that.</p>
<p>Note that an attribute declaration of the form</p>
<pre>    has Tail $wagger .= new(...)</pre>
<p>might not do what you want done when you want it done, if
what you want done is to create a new <code>Dog</code> object each time an object
is built.  For that you'd have to say:</p>
<pre>    has Tail $wagger = { .new(...) }</pre>
<p>or equivalently,</p>
<pre>    has Tail $wagger will build { .new(...) }</pre>
<p>But leaving aside such timing issues, you should generally think of
the <code>.=</code> operator more as a variant on <code>.</code> than a variant on <code>+=</code>.
It can, for instance, turn any non-mutating method call into a
mutating method:</p>
<pre>    @array.=sort;	# sort @array in place
    .=lc;		# lowercase $_ in place</pre>
<p>This presumes, of course, that the method's invocant and return
value are of compatible types.  Some classes will wish to define special
in-place mutators.  The syntax for that is:</p>
<pre>    method self:sort (Array @a is rw) {...}</pre>
<p>[Update: That's now <code>self:&lt;sort&gt;</code> instead.]</p>
<p>It is illegal to use <code>return</code> from such a routine, since the invocant
is automatically returned.  If you do not declare the invocant, the
default invocant is automatically considered &quot;<code>rw</code>&quot;.  If you do not
supply a mutating version, one is autogenerated for you based on
the corresponding copy operator.</p>
<a name='Object Deconstruction'></a><h1>Object Deconstruction</h1>
<p>Object destruction is no longer guaranteed to be &quot;timely&quot; in Perl 6.
It happens when the garbage collector gets around to it.  (Though there
will be ways to emulate Perl 5 end-of-scope cleanup.)</p>
<p>As with object creation, object destruction is recursive.  Unlike creation,
it must proceed in the opposite order.</p>
<a name='DESTROYALL'></a><h2>DESTROYALL</h2>
<p>The <code>DESTROYALL</code> routine is the counterpart to the <code>BUILDALL</code>
routine.  Similarly, the default definition is normally sufficient
for the needs of most classes.  <code>DESTROYALL</code> first calls <code>DESTROY</code>
on the current class, and then delegates to the <code>DESTROYALL</code> of any
parent classes.  In this way the pieces of the object are disassembled
in the correct order, from most derived to least derived.</p>
<a name='DESTROY'></a><h2>DESTROY</h2>
<p>As with Perl 5, all the memory deallocation is done for you, so you
really only need to define <code>DESTROY</code> if you have to release external
resources such as files.</p>
<p>Since <code>DESTROY</code> is the opposite of <code>BUILD</code>, if any attribute
declaration has a &quot;<code>destroy</code>&quot; property, that property (presumably
a closure) is evaluated before the main block of <code>DESTROY</code>.
This happens even if you don't declare a <code>DESTROY</code>.</p>
<p>(The &quot;<code>build</code>&quot; and &quot;<code>destroy</code>&quot; traits are the only way for roles to let
their preferences be made known at <code>BUILD</code> and <code>DESTROY</code> time.
It follows that any role that does not define an attribute cannot
participate in building and destroying except by defining a method
that <code>BUILD</code> or <code>DESTROY</code> might call.  In other words, stateless
roles aren't allowed to muck around with the object's state.  This is
construed as a feature.)</p>
<a name='Dispatch Mechanisms'></a><h1>Dispatch Mechanisms</h1>
<p>Perl 6 supports both single dispatch (traditional OO) and multiple dispatch
(also known as &quot;multimethod dispatch&quot;, but we try to avoid that term).</p>
<a name='Single Dispatch'></a><h2>Single Dispatch</h2>
<p>Single dispatch looks up which method to run solely on the basis of
the type of the first argument, the invocant.  A single-dispatch call
distinguishes the invocant syntactically (unlike a multiple-dispatch
call, which looks like a subroutine call, or even an operator.)</p>
<p>Basically, anything can be an invocant as long as it fills the <code>Dispatch</code>
role, which provides a <code>.dispatcher</code> method.  This includes ordinary
objects, class objects, and (in some cases) even varieties of <code>undef</code>
that happen to know what class of thing they aren't (yet).</p>
<p>[Update: It is unlikely that there will be a <code>.dispatcher</code> method.  This
is all delegated to the <code>.meta</code> object now, at least in the abstract.]</p>
<p>Simple single dispatch is specified with the dot operator, or its
indirect object equivalent:</p>
<pre>    $object.meth(@args)	  # always calls public .meth
           .meth(@args)	  # unary form
    meth $object: @args	  # indirect object form</pre>
<p>There are variants on the dot form indicated by the character after
the dot.  (None of these variants allows indirect object syntax.)
The private dispatcher only ever dispatches to the current class or
its proxies, so it's really more like a subroutine call in disguise:</p>
<pre>    $object.:meth(@args)  # always calls private :meth
           .:meth(@args)  # unary form</pre>
<p>[Update: Uses <code>!</code> now, no unary form.]</p>
<p>It is an error to use <code>.:</code> unless there is a correspondingly named
&quot;colon&quot; method in the appropriate class, just as it is an error to
use <code>.</code> when no method can be found of that name.  Unlike the <code>.:</code>
operator, which can have only one candidate method, the <code>.</code> operator
potentially generates a list of candidates, and allows methods in that
candidate list to defer to subsequent methods in other classes until
a candidate has been found that is willing to handle the dispatch.</p>
<p>In addition to the <code>.:</code> and <code>.=</code> operators, there are three other
dot variants that can be used if it's not known how many methods are
willing to handle the dispatch:</p>
<pre>    $object.?meth(@args)  # calls method if there is one
           .?meth(@args)  # unary form
    $object.*meth(@args)  # calls all methods (0 or more)
           .*meth(@args)  # unary form
    $object.+meth(@args)  # calls all methods (1 or more)
           .+meth(@args)  # unary form</pre>
<p>The <code>.*</code> and <code>.+</code> versions are generally only useful for calling
submethods, or methods that are otherwise expected to work like
submethods.  They return a list of all the successful return values.
The <code>.?</code> operator either returns the one successful result, or
undef if no appropriate method is found.  Like the corresponding
regex modifiers, <code>?</code> means &quot;0 or 1&quot;, while <code>*</code> means &quot;0 or more&quot;,
and <code>+</code> means &quot;1 or more&quot;.  Ordinary <code>.</code> means &quot;exactly one&quot;.
Here are some sample implementations, though of course these are
probably implemented in C for maximum efficiency:</p>
<pre>    # Implements . (or .? if :maybe is set).
    sub CALLONE ($obj, $methname, +$maybe, *%opt, *@args) {
	my $startclass = $obj.dispatcher() // fail &quot;No dispatcher: $obj&quot;;
      METHOD:
        for WALKMETH($startclass, :method($methname), %opt) -&gt; &amp;meth {
	    return meth($obj, @args);
        }
	fail qq(Can't locate method &quot;$methname&quot; via class &quot;$startclass&quot;)
	    unless $maybe;
	return;
    }</pre>
<p>With this dispatcher you can continue by saying &quot;<code>next METHOD</code>&quot;.
This allows methods to &quot;failover&quot; to other methods if they choose
not to handle the request themselves.</p>
<pre>    # Implements .+ (or .* if :maybe is set).
    #   Add :force to redispatch in every class
    sub CALLALL ($obj, $methname, +$maybe, +$force, *%opt, *@args) {
	my $startclass = $obj.dispatcher() // fail &quot;No dispatcher: $obj&quot;;
        my @results = gather {
	    if $force {
	      METHOD:
		for WALKCLASS($startclass, %opt) -&gt; $class {
		    take $obj.::($class)::$methname(*@args) # redispatch
		}
	    }
	    else {
	      METHOD:
		for WALKMETH($startclass, :method($methname), %opt) -&gt; &amp;meth {
		    take meth($obj,*@args);
		}
	    }
        }
	return @results if @results or $maybe;
	fail qq(Can't locate method &quot;$methname&quot; via class &quot;$startclass&quot;);
    }</pre>
<p>This one you can quit early by saying &quot;<code>last METHOD</code>&quot;.  Notice that
both of these dispatchers cheat by calling a method as if it were
a sub.  You may only do that by taking a reference to the method, and
calling it as a subroutine, passing the object as the first argument.
This is the only way to call a virtual method non-virtually in Perl.
If you try to call a method directly as a subroutine, Perl will ignore
the method, look for a subroutine of that name elsewhere, probably
not find it, and complain bitterly.  (Or find the wrong subroutine,
and execute it, after which you will complain bitterly.)</p>
<p>We snuck in an example the new <code>gather</code>/<code>take</code> construct.  It is still
somewhat conjectural.</p>
<a name='Calling Superclasses, and Not-So-Superclasses'></a><h2>Calling Superclasses, and Not-So-Superclasses</h2>
<p>Perl 5 supplies a pseudoclass, <code>SUPER::</code>, that redirects dispatch to
a parent class's method.  That's often the wrong thing to do, though,
in part because under MI you may have more than one parent class, and
also because you might have sibling classes that also need to have
the given method triggered.  Even if <code>SUPER</code> is smart enough to visit
multiple parent classes, and even if all your classes cooperate and
call <code>SUPER</code> at the right time, the depth first order of visitation
might be the wrong order, especially under diamond inheritance.
Still, if you know that your parent classes use <code>SUPER</code>, or you're
calling into a language with <code>SUPER</code> semantics (such as Perl 5)
then you should probably use <code>SUPER</code> semantics too, or you'll end up
calling your parent's parents in duplicate.  However, since use of
<code>SUPER</code> is slightly discouraged, we Huffman code it a bit longer in
Perl 6.  Remember the <code>*%opt</code> parameters to the dispatchers above?
That comes in as a parameterized pseudoclass called <code>WALK</code>.</p>
<pre>    $obj.*WALK[:super]::method(@args)</pre>
<p>That limits the call to only those immediate super classes that define
the method.  Note the star in the example.  If you really want the Perl
5 semantics, leave the star out, and you'll only get the first existing
parent method of that name.  (Why you'd want that is beyond me.)</p>
<p>Actually, we'll probably still allow <code>SUPER::</code> as a shorthand for
<code>WALK[:super]::</code>, since people will just hack it in anyway if we
don't provide it...</p>
<p>If you think about it, every ordinary dispatch has an implicit
<code>WALK</code> modifier on the front that just happens to default to
<code>WALK[:canonical]</code>.  That is, the dispatcher looks for methods in
the canonical order.  But you could say <code>WALK[:depth]</code> to get Perl
5's order, or you could say <code>WALK[:descendant]</code> to get an order
approximating the order of construction, or <code>WALK[:ascendant]</code> to
get an order approximating the order of destruction.  You could say
<code>WALK[:omit(SomeClass)]</code> to call all classes not equivalent to or
derived from <code>SomeClass</code>.  For instance, to call all super classes,
and not just your immediate parents, you could say <code>WALK[:omit(::_)]</code>
to skip the current lexical class or anything derived from it.</p>
<p>[Update: The lexical class is now named <code>::?CLASS</code>.]</p>
<p>But again, that's not usually the right thing to do.  If your base classes
are all willing to cooperate, it's much better to simply call</p>
<pre>    $obj.method(@args)</pre>
<p>and then let each of the implementations of the method defer to the
next one when they're done with their part of it.  If any method says
&quot;<code>next METHOD</code>&quot;, it automatically iterates the loop of the dispatcher
and finds the next method to dispatch to, even if that method comes
from a sibling class rather than a parent class.  The next method
is called with the same arguments as originally supplied.</p>
<p>That presupposes that the entire set of methods knows to call
&quot;next&quot; appropriately.  This is not always the case.  In fact,
if they don't all call next, it's likely that none of them does.
And maybe just knowing whether or not they do is considered a violation
of encapsulation.  In any case, if you still want to call all the
methods without their active cooperation, then use the star form:</p>
<pre>    $obj.*method(@args)</pre>
<p>Then the various methods don't have to do anything to call the next
method--it happens automatically by default.  In this case a method
has to do something special if it wants to <i>stop</i> the dispatch.
Naturally, that something is to call &quot;<code>last METHOD</code>&quot;, which terminates
the dispatch loop early.</p>
<p>Now, sometimes you want to call the next method, but you want to
change the arguments so that the next method doesn't get the original
argument list.  This is done with deep magic.  If you use the <code>call</code>
keyword in an ordinary (nonwrapper) method, it steals the rest of
the dispatch list from the outer loop and redispatches to the next
method with the new arguments:</p>
<pre>    @retvals = call(@newargs)
    return @retvals;</pre>
<p>And unlike with &quot;<code>next METHOD</code>&quot;, control returns to this method following
the call.  It returns the results of the subsequent method calls, which
you should return so that your outer dispatcher can add them to the
return values it already gathered.</p>
<p>Note that &quot;<code>next METHOD</code>&quot; and &quot;<code>last METHOD</code>&quot; can typically be spelt
&quot;<code>next</code>&quot; and &quot;<code>last</code>&quot; unless they are in an inner loop.</p>
<a name='Parallel Dispatch'></a><h2>Parallel Dispatch</h2>
<p>By default the various dot operators call a method on a single
object, even if it ends up calling multiple methods for that object.
Since a method call is essentially a unary postfix operator, however,
you can use it as a hyper operator on a list of objects:</p>
<pre>    @object».meth(@args)	# Call one for each or fail
    @object».?meth(@args)	# Call one for each if available
    @object».*meth(@args)	# Call all available for each
    @object».+meth(@args)	# Call one or more for each</pre>
<p>Note that with the last two, if a method uses &quot;<code>last METHOD</code>&quot;,
it doesn't bomb out of the &quot;hyper&quot; loop, but just goes on to the
next entry.  One can always bomb out of the hyperloop with a real
exception, of course.  And maybe with &quot;<code>last HYPER</code>&quot;, depending on
how hyper's implicit iteration is implemented.</p>
<p>If you want to use an array for serial rather than parallel method
calling, see Delegation, which lets you set up cascading handlers.</p>
<a name='WALKCLASS and WALKMETH Caching'></a><h2>WALKCLASS and WALKMETH Caching</h2>
<p><code>WALKCLASS</code> generates a list of matching classes.  <code>WALKMETH</code>
generates a list of method references from matching classes.</p>
<p>The <code>WALKCLASS</code> and <code>WALKMETH</code> routines used in the sample dispatch
code need to cache their results so that every dispatch doesn't
have to traverse the inheritance tree again, but just consult the
preconstructed list in order.  However, if there are changes to any
of the classes involved, then someone needs to call the appropriate
cache clear method to make sure that the inheritance is recalculated.</p>
<p><code>WALKCLASS</code>/<code>WALKMETH</code> options include some that specify ordering:</p>
<pre>    :canonical      # canonical dispatch order
    :ascendant      # most-derived first, like destruction order
    :descendant     # least-derived first, like construction order
    :preorder       # like Perl 5 dispatch
    :breadth        # like multimethod dispatch</pre>
<p>and some that specify selection criteria:</p>
<pre>    :super		# only immediate parent classes
    :method(Str)	# only classes containing method declaration
    :omit(Selector)	# only classes that don't match selector
    :include(Selector)	# only classes that match selector</pre>
<p>Note that <code>:method(Str)</code> selects classes that merely have methods
declared, not necessarily defined.  A declaration without a definition
probably implies that they intend to autoload a definition, so
we should call the stub anyway.  In fact, Perl 6 differentiates an
<code>AUTOMETHDEF</code> from <code>AUTOLOAD</code>.  <code>AUTOLOAD</code> works as it does in
Perl 5.  <code>AUTOMETHDEF</code> is never called unless there is already a
declaration of the stub (or equivalently, <code>AUTOMETH</code> faked a stub.)</p>
<p>[Update: Those autoloaders are now called <code>AUTODEF</code> and <code>CANDO</code>.]</p>
<p>It would be possible to just define everything in terms of <code>WALKCLASS</code>,
but that would imply looking up each method name twice, once inside
<code>WALKCLASS</code> to see if the method exists in the current class, and
once again outside in order to call it.  Even if <code>WALKCLASS</code> caches
the cache list, it wouldn't cache the derived method list, so it's
better to have a separate cache for that, controlled by <code>WALKMETH</code>,
since that's the common case and has to be fast.</p>
<p>(Again, this is all abstract, and is probably implemented in gloriously
grungy C code.  Nevertheless, you can probably call <code>WALKCLASS</code> and
<code>WALKMETH</code> yourself if you feel like writing your own dispatcher.)</p>
<a name='Multiple Dispatch'></a><h1>Multiple Dispatch</h1>
<p>Multiple dispatch is based on the notion that methods often mediate the
relationships of multiple objects of diverse types, and therefore the
first object in the argument list should not be privileged over other
objects in the argument list when it comes to selecting which method
to run.  In this view, methods aren't subservient to a particular
class, but are independent agents.  A set of independent-minded,
identically named methods use the class hierarchy to do pattern
matching on the argument list and decide among themselves which method
can best handle the given set of arguments.</p>
<p>The Perl approach is, of course, that sometimes you want to distinguish
the first invocant, and sometimes you don't.  The interaction of
these two approaches gets, um, interesting.  But the basic notion
is to let the caller specify which approach is expected, and then,
where it makes sense, fall back on the other approach when the first
one fails.  Underlying all this is the Principle of Least Surprise.
Do not confuse this with the Principle of Zero Surprise, which usually
means you've just swept the real surprises under some else's carpet.
(There's a certain amount of surprise you can't go below--the
Heisenberg Uncertainty Principle applies to software too.)</p>
<p>With traditional multimethods, all methods live in the same global
namespace.  Perl 6 takes a different approach--we still keep all the
traditional Perl namespaces (lexical, package, global) and we still
search for names the same way (outward through the lexical scopes,
then the current package, then the global <code>*</code> namespace; or upward in
the class hierarchy).  Then we simply claim that, under multiple
dispatch, the &quot;long name&quot; of any multi routine includes its signature,
and that visibility is based on the long name.  So an inner or derived
multi only hides an outer or base multi of the same name <i>and</i> the
same signature.  (Routines not declared &quot;<code>multi</code>&quot; still hide everything
in the traditional fashion.)</p>
<p>To put it another way, the multiple dispatch always works when both
the caller and the callee agree that that's how it should work.
(And in some cases it also works when it ought to work, even if they
don't agree--sort of a &quot;common law&quot; multimethod, as it were...)</p>
<a name='Declaration of Multiple Dispatch Routines'></a><h2>Declaration of Multiple Dispatch Routines</h2>
<p>A callee agrees to the multiple dispatch &quot;contract&quot; by including
the word &quot;<code>multi</code>&quot; in the declaration of the routine in question.
It essentially says, &quot;Ordinarily this would be a unique name, but
it's okay to have duplicates of this name (the short name) that are
differentiated by signatures (the long name).&quot;</p>
<p>Looking at it from the other end, leaving the &quot;<code>multi</code>&quot; out says &quot;I am
a perfect match for any signature--don't bother looking any further
outward or upward.&quot;  In other words, the standard non-multi semantics.</p>
<p>You may not declare a multi in the same scope as a non-multi.
However, as long as they are in different scopes, you can have a
single non-multi inside a set of multis, or a set of multis inside
a single non-multi.  You can even have a set of multis inside a non-multi
inside a set of multis.  Indeed, this is how you hide all the outer
multis so that only the inner multi's long names are considered.
(And if no long name matches, you get the intermediate non-multi as
a kind of backstop.)  The same policy applies to both nested lexical
scopes and derived subclasses.</p>
<p>[Update: Now you can declare a &quot;first multi&quot; that is simulataneously
an ordinary sub and the final arbiter of subsequent multi declarations
in this scope.  This is done with the &quot;<code>proto</code>&quot; keyword in place of
the &quot;<code>multi</code>&quot; keyword&quot;.  Oh, and the &quot;<code>sub</code>&quot; is optional with either
&quot;<code>multi</code>&quot; or &quot;<code>proto</code>&quot;.]</p>
<p>Actually, up till now we've been oversimplifying the concept of
&quot;long name&quot; slightly.  The long name includes only that part of
the signature up to the first colon.  If there is no colon, then the
entire signature is part of the long name.  (You can have more colons,
in which case the additional arguments function as tie breakers if
the original set of long names is insufficient to prevent a tie.)</p>
<p>[Update: The actual, most-unique &quot;long name&quot; is really till the last colon,
not the first.  But the tiebreaking still happens as described above.]</p>
<p>So sometimes we'll probably slip and say &quot;signature&quot; when we mean
&quot;long name&quot;.  We pray your indulgence.</p>
<a name='multi sub'></a><h3>multi sub</h3>
<p>A multi sub in any scope hides any multi sub with the same &quot;long name&quot;
in any outer scope.  It does not hide subs with the same short name
but a different signature.  Er, long name, I mean...</p>
<a name='multi sub * (tradition multimethods)'></a><h3>multi sub * (tradition multimethods)</h3>
<p>If you want a multi that is visible in all namespaces (that don't
hide the long name), then declare the name in the global name space,
indicated in Perl 6 with a <code>*</code>.  Most of the so-called &quot;built-ins&quot;
are declared this way:</p>
<pre>    multi sub *push (Array $array, *@args) {...}
    multi sub *infix:+ (Num $x, Num $y) returns Num {...}
    multi sub *infix:.. (Int $x, Int $y: Int ?$by) returns Ranger {...}</pre>
<p>[Update: Those are now named <code>infix:&lt;+&gt;</code> and <code>infix:&lt;..&gt;</code>.]</p>
<p>Note the use of colon in the last example to exclude <code>$by</code> as part of
the long name.  The range operator is dispatched only on the types of
its two main arguments.</p>
<a name='multi method'></a><h3>multi method</h3>
<p>If you declare a method with <code>multi</code>, then that method hides any base class
method with the same long name.  It does not hide methods with the same
short name but a different signature when called as a multimethod.
(It does hide methods when called under single dispatch, in which
case the first invocant is treated as the <i>only</i> invocant regardless
of where you put the colon.  Just because a method is declared with
<code>multi</code> doesn't make it invisible to single dispatch.)</p>
<p>Unlike a regular method declaration, there is no implied invocant in
the syntax of a multi method.  A method declared as multi <i>must</i>
declare all its invocants so that there's no ambiguity as to the
meaning of the first colon.  With a multi method, it always means the end of
the long name.  (With a non-multi, it always means that the optional
invocant declaration is present.)</p>
<a name='multi submethod'></a><h3>multi submethod</h3>
<p>Submethods may be declared with <code>multi</code>, in which case visibility
works the same as for ordinary methods.  However, a submethod has
the additional constraint that the first invocant must be an exact
class match.  Which effectively means that a submethod is first single
dispatched to the class, and then the appropriate submethod within
that class is selected, ignoring any other class's submethods of the
same name.</p>
<p>[Update: Multi submethods are visible to both the single dispatch and
multiple dispatcher.  Multi methods are visible only within the constraints
of single dispatch.]</p>
<a name='multi rule'></a><h3>multi rule</h3>
<p>Since rules are just methods in disguise, you can have multi rules as
well.  (Of course, that doesn't do you a lot of good unless you have
rules with different signatures, which is unusual.)</p>
<a name='multi submethod BUILD'></a><h3>multi submethod BUILD</h3>
<p>It is not likely that Perl 6.0.0 will support multiple dispatch on
named arguments, but only on positional arguments.  Since all the extra
arguments to a <code>BUILD</code> routine come in as named arguments, you probably
can't usefully multi a <code>BUILD</code> (yet).  However, we should not do anything
that precludes multiple <code>BUILD</code> submethods in the future.  Which means we
should probably enforce the presence of a colon before the first named
argument declaration in any multi signature, so that the semantics
don't suddenly change if and when we start supporting multiple dispatch
that includes named arguments as part of the long name.</p>
<a name='multi method constructors'></a><h3>multi method constructors</h3>
<p>To the extent that you declare constructors (such as <code>.new</code>) with
positional arguments, you can use <code>multi</code> on them in 6.0.0.</p>
<a name='Calling via Multiple Dispatch'></a><h2>Calling via Multiple Dispatch</h2>
<p>As we mentioned, multiple dispatch is enabled by agreement of both
caller and callee.  From the caller's point of view, you invoke
multiple dispatch simply by calling with subroutine call syntax instead
of method call syntax.  It's then up to the dispatcher to figure out
which of the arguments are invocants and which ones are just options.
(In the case where the innermost visible subroutine is declared non-multi,
this degenerates to the Perl 5 semantics of subroutine calls.)  This
approach lets you refactor a simple subroutine into a more nuanced
set of subroutines without changing how the subroutines are called
at all.  That makes this sort of refactoring drop-dead simple.  (Or
at least as simple as refactoring ever gets...)</p>
<p>It's a little harder to refactor between single dispatch and multiple
dispatch, but a good argument could be made that it <i>should</i> be harder
to do that, because you're going to have to think through a lot more
things in that case anyway.</p>
<p>Anyway, here's the basic relationship between single dispatch and multiple
dispatch.  Single dispatch is more familiar, so we'll discuss multiple
dispatch first.</p>
<a name='Multiple dispatch semantics'></a><h3>Multiple dispatch semantics</h3>
<p>Whenever you make a call using subroutine call syntax, it's a candidate
for multiple dispatch.  A search is made for an appropriate subroutine
declaration.  As in Perl 5, this search goes outward through the
lexical scopes, then through the current package and on to the
global namespace (represented in Perl 6 with an initial * for the
&quot;wildcard&quot; package name).  If the name found is not a multi, then
it's a good old-fashioned sub call, and no multiple dispatch is done.
End of story.</p>
<p>[Update: A &quot;proto&quot; counts as a &quot;sub&quot; here, not as a &quot;multi&quot;.]</p>
<p>However, if the first declaration we come to is a multi, then lots of
interesting stuff happens.  (Fortunately for our performance, most of
this interesting stuff can happen at compile time, or upon first use.)
The basic idea is that we will collect a complete list of candidates
before we decide which one to call.</p>
<p>So the search continues outward, collecting all sub declarations
with the same short name but different long names.  (We can ignore
outer declarations that are hidden by an inner declaration with the
same long name.)  If we run into a scope with a non-multi declaration,
then we're done generating our candidate list, and we can skip the
next paragraph.</p>
<p>After going all the way out to the global scope, we then examine the
type of the first argument as if we were about to do single dispatch on
it.  We then visit any classes that would have been single dispatched,
in most-derived to least-derived order, and for each of those classes
we add into our candidate list any methods declared multi, plus all
the single invocant methods, whether or not they were declared multi!
In other words, we just add in all the methods declared in the class
as a subset of the candidates.  (There are reasons for this that we'll
discuss below.)  Anyway, just as with nested lexical scopes, if two
methods have the same long name, the more derived one hides the less
derived one.  And if there's a class in which the method of the same
short name is not declared multi, it serves as a &quot;stopper&quot;, just as a
non-multi sub does in a lexical scope.  (Though that &quot;stopper&quot; method
can of course redispatch further up the inheritance tree, just as a
&quot;stopper&quot; lexical sub can always call further outward if it wants to.)</p>
<p>[Update: We now have the &quot;proto&quot; keyword to specifically mark such
a routine.  It also lets the routine supply known argument names for
any multis found in the lexical scope, so the compiler can be smart
about mapping named args to positionals.]</p>
<p>Now we have our list of candidates, which may or may not include every
sub and method with the same short name, depending on whether we hit a
&quot;stopper&quot;.  Anyway, once we know the candidate list, it is sorted into
order of distance from the actual argument types.  Any exact match on a
parameter type is distance 0.  Any miss by a single level of derivation
counts as a distance of 1.  Any violation of a hard constraint (such as
having too many arguments for the number of parameters, or violating
a subtype check on a type that does constraint checking, or missing
the exact type on a submethod) is effectively an infinite distance,
and disqualifies the candidate completely.</p>
<p>Once we have our list of candidates sorted, we simply call the first
one on the list, unless there's more than one &quot;first one&quot; on the
list, in which case we look to see if one of them is declared to be
the default.  If so, we call it.  If not, we die.</p>
<p>So if there's a tie, the default routine is in charge of subsequent
behavior:</p>
<pre>    # Pick next best at random...
    multi sub foo (BaseA $a, BaseB $b) is default {
        next METHOD;
    }

    # Give up at first ambiguity...
    multi sub bar (BaseA $a, BaseB $b) is default {
        last METHOD;
    }

    # Invoke my least-derived ancestor
    multi sub baz (BaseA $a, BaseB $b) is default {
        my @ambiguities = WALKMETH($startclass, :method('baz'))
	    or last METHOD;
        pop(@ambiguities).($a, $b);
    }

    # Invoke most generic candidate (often a good fall-back)...
    multi sub baz (BaseA $a, BaseB $b) is default {
        my @ambiguities = @CALLER::methods or last METHOD;
        pop(@ambiguities).value.($a, $b);
    }</pre>
<p>In many cases, of course, the default routine won't redispatch, but simply
do something generically appropriate.</p>
<p>[Update: We probably aren't using the &quot;Manhattan&quot; distance indicated above.]</p>
<a name='Single dispatch semantics'></a><h3>Single dispatch semantics</h3>
<p>If you use the dot notation, you are explicitly calling single dispatch.
By default, if single dispatch doesn't find a suitable method, it does
a &quot;failsoft&quot; to multiple dispatch, pretending that you called a subroutine
with the invocant passed as the first argument.  (Multiple dispatch doesn't
need to failsoft to single dispatch since all single dispatch methods are
included as a subset of the multiple dispatch candidates anyway.)</p>
<p>This failsoft behavior can be modified by lexically scoped pragma.
If you say</p>
<pre>    use dispatch :failhard</pre>
<p>then single dispatch will be totally unforgiving as it is in Perl 5.
Or you can tell single dispatch to go away:</p>
<pre>    use dispatch :multi</pre>
<p>in which case all your dot notation is treated as a sub call.  That is, any</p>
<pre>    $obj.method(1,2,3)</pre>
<p>in the lexical scope acts like you'd said:</p>
<pre>    method($obj,1,2,3)</pre>
<p>If single dispatch locates a class that defines the method, but the
method in question turns out to be a set of one or more multi methods,
then, the single dispatch fails immediately and a multiple dispatch
is done, with the additional constraint that only multis within that
class are considered.
(If you wanted the first argument to do loose matching as well,
you should have called it as a multimethod in the first place.)</p>
<a name='Indirect objects'></a><h3>Indirect objects</h3>
<p>If you use indirect object syntax with an explicit colon, it is
exactly equivalent to dot notation in its semantics.</p>
<p>However, one-argument subs are inherently ambiguous, because Perl 6
does not require the colon on indirect objects without arguments.
That is, if you say:</p>
<pre>    print $fh</pre>
<p>it's not clear whether you mean</p>
<pre>    $fh.print</pre>
<p>or</p>
<pre>    print($fh)</pre>
<p>As it happens, we've defined the semantics so that it doesn't matter.
Since all single invocant methods are included automatically in
multimethod dispatch, and since multiple dispatch degenerates to
single dispatch when there's only one invocant, it doesn't matter
which way you write it.  The effect is the same either way.  (Unless
you've defined your own non-multi print routine in a surrounding
lexical scope.  But then, if you've done that, you probably did it
on purpose <i>precisely</i> because you wanted to disable the default
dispatch semantics.)</p>
<a name='Meaning of &quot;next METHOD&quot;'></a><h2>Meaning of &quot;next METHOD&quot;</h2>
<p>Within the context of a multimethod dispatch, &quot;<code>next METHOD</code>&quot; means to
try the next best match, if unambiguous, or else the marked default
method.  From within the default method it means just pick the next
in the list even if it's ambiguous.  The dispatch list is actually
kept in <code>@CALLER::methods</code>, which is a list of pairs, the key of each
indicating the &quot;distance&quot; rating, and the value of each containing
a reference to the method to call (as a sub ref).</p>
<p>[Update: A proto routine can't use &quot;<code>next METHOD</code>&quot; because the original
dispatch list is exhausted.  Maybe.  If so, we can arrange for <code>call()</code>
to propagate the call outward, as if the proto routine is a wrapper
around the rest of the world.]</p>
<a name='Making Fiends, er, Friends.'></a><h2>Making Fiends, er, Friends.</h2>
<p>If you want to directly access the attributes of a class, your multi
must be declared within the scope of that class.  Attributes are
never directly visible outside a class.  This makes it difficult to
write an efficient multimethod that knows about the internals of two
different classes.  However, it's possible for private accessors to
be visible outside your class under one condition.  If your class
declares that another class is trusted, that other class can see the
private accessors of your class.  If the other class declares that
you are trusted, then you can see its private accessor methods.
The trust relationship is not necessarily symmetrical.
This lets you have an architecture where classes by and large
don't trust each other, but they all trust a single well-guarded
&quot;<code>multi</code>-plexor&quot; class that keeps everyone else in line.</p>
<p>The syntax for trusting another class is simply:</p>
<pre>    class MyClass {
	trusts Yourclass;
	...
    }</pre>
<p>It's not clear whether roles should be allowed to grant trust.
In the absence of evidence to the contrary, I'm inclined to say not.
We can always relax that later if, after many large, longitudinal,
double-blind studies, it turns out to be both safe and effective.</p>
<p>[Update: The intent of the previous paragraph was to describe whether
a role could grant trust on behalf of the composed class, but it
was ambiguously stated, and sometimes misinterpreted.  It seems to me
that a role could grant trust to private routines in its own scope,
however, since they're basically just sub calls anyway.  On the other
hand, the relationship of the role's package namespace to its eventual
lexical namespace is perhaps problematic.  At some point the object
has to keep track of all its cloned role closures and provide the
right one to private sub callers.]</p>
<a name='Overloading'></a><h1>Overloading</h1>
<p>In Perl 5 overloading was this big special deal that had to have
special hooks inserted all over the C code to catch various operations
on overloaded types and do something special with them.  In Perl 6,
that just all falls out naturally from multiple dispatch.  The only
other part of the trick is to consider operators to be function calls
in disguise.  So in Perl 6 the real name of an operator is composed of
a grammatical context identifier, a colon, and then the name of the
operator as you usually see it.  The common context identifiers are
&quot;prefix&quot;, &quot;infix&quot;, &quot;postfix&quot;, &quot;circumfix&quot;, and &quot;term&quot;, but there are
others.</p>
<p>So when you say something like</p>
<pre>    $x = &lt;$a++ * <a href='mailto:-@b.'>-@b.</a>[...]&gt;;</pre>
<p>you're really saying something like this:</p>
<pre>    $x = circumfix:&lt;&gt;(
	infix:*(
	    postfix:++($a),
	    prefix:-(
		infix:.(
		    @b,
		    circumfix:[](
			term:...();
		    )
		)
	    )
	)
    )</pre>
<p>[Update: All the operator names need to be quoted now as a hash
subscript or slice.  And instead of breaking <code>.[]</code> into <code>.</code> and
<code>[]</code>, there is now a <code>postcircumfix</code> grammatical category.  So we
have:</p>
<pre>    $x = circumfix:«&lt; &gt;»(
	infix:&lt;*&gt;(
	    postfix:&lt;++&gt;($a),
	    prefix:&lt;-&gt;(
		postcircumfix:&lt;[ ]&gt;(
		    @b,
		    term:&lt;...&gt;();
		)
	    )
	)
    )</pre>
<p>Except that circumfix <code>&lt;...&gt;</code> is a quoting operator these days.
many of the examples using French quotes in this Apocalypse are now
written with regular angles.]</p>
<p>Perl 5 had special key names representing stringification and numification.
In Perl 6 these naturally fall out if you define:</p>
<pre>    method prefix:+ () {...}	# what we do in numeric context
    method prefix:~ () {...}	# what we do in string context</pre>
<p>[Update: Here and below, it's <code>prefix:&lt;+&gt;</code> etc.]</p>
<p>Likewise you can define what to return in boolean context:</p>
<pre>    method prefix:? () {...}	# what we do in boolean context</pre>
<p>Integer context is, of course, just an ordinary method:</p>
<pre>    method int () {...} 	# what we do in integer context</pre>
<p>These can be defined as normal methods since single-invocant multi
subs degenerate to standard methods anyway.  C++ programmers will tend
to feel comfy defining these as methods.  But others may prefer to
declare them as multi subs for consistency with binary operators.
In which case they'd look more like this:</p>
<pre>    multi sub *prefix:+ (Us $us) {...}	 # what we do in numeric context
    multi sub *prefix:~ (Us $us) {...}	 # what we do in string context
    multi sub *prefix:? (Us $us) {...}	 # what we do in string context
    multi sub *prefix:int (Us $us) {...} # what we do in integer context</pre>
<p>Coercions to other classes can also be defined:</p>
<pre>    multi sub *coerce:as (Us $us, Them ::to) { to.transmogrify($us) }</pre>
<p>Such coercions allow both explicit conversion:</p>
<pre>    $them = $us as Them;</pre>
<p>as well as implicit conversions:</p>
<pre>    my Them $them = $us;</pre>
<a name='Binary Ops'></a><h2>Binary Ops</h2>
<p>Binary operators should generally be defined as multi subs:</p>
<pre>    multi sub infix:+ (Us $us, Us $ustoo) {...}
    multi sub infix:+ (Us $us, Them $them) is commutative {...}</pre>
<p>[Update: And these are <code>infix:&lt;+&gt;</code> now.]</p>
<p>The &quot;<code>is commutative</code>&quot; trait installs an additional autogenerated sub
with the invocant arguments reversed, but with the same semantics otherwise.
So the declaration above effectively autogenerates this:</p>
<pre>    multi sub infix:+ (Them $them, Us $us) {...}</pre>
<p>Of course, there's no need for that if the two arguments have the
same type.  And there might not actually be an autogenerated other
subroutine in any case, if the implementation can be smart enough
to simply swap the two arguments when it needs to.  However it gets
implemented, note that there's no need for Perl 5's &quot;reversed arguments
flag&quot; kludge, since we reverse the parameter name bindings along
with the types.  Perl 5 couldn't do that because it had no control
of the signature from the compiler's point of view.</p>
<p>See Apocalypse 6 for much more on the definition of user-defined
operators, their precedence, and their associativity.  Some of it
might even still be accurate.</p>
<p>[Update: Nowadays see Synopsis 6 instead.]</p>
<a name='Class Composition with Roles'></a><h1>Class Composition with Roles</h1>
<p>Objects have many kinds of relationships with other objects.  One of
the pitfalls of the early OO movement was to encourage people to
model many relationships with inheritance that weren't really
&quot;isa&quot; relationships.  Various languages have sought to redress
this deficiency in various ways, with varying degrees of success.
With Perl 6 we'd like to back off a step and allow the user to
define abstract relationships between classes without committing to
a particular implementation.</p>
<p>More specifically, we buy the argument of the Traits paper (see
<a href='http://www.cse.ogi.edu/~black/publications/TR_CSE_02-012.pdf)' target='_blank'>www.cse.ogi.edu</a>
that classes should not be used both to manage objects and to manage
code reuse.  It needs to be possible to separate those concerns.
Since a lot of the code that people want to reuse is that which
manages non-isa object relationships, that's what we should abstract
out from classes.</p>
<p>That abstraction we are calling a role.  Roles can encompass both
interface and implementation of object relationships.  A role without
implementation degenerates to an interface.  A role without interface
degenerates to privately instantiated generics.  But the typical role
will provide both interface and at least a default implementation.</p>
<p>Unlike the Traits paper, we will allow state as part of our
implementation.  This is necessary if we are to abstract out the
delegation decision.  We feel that the decision to delegate rather
than compose a sub-object is a matter of implementation, and therefore
that decision should be encapsulated (or at least be allowed to be
encapsulated) in a role.  This allows you to refactor a problem by
redefining one or more roles without having to doctor all the classes
that make use of those roles.  This is a great way to turn your huge,
glorious &quot;god object&quot; into a cooperating set of objects that know
how to delegate to each other.</p>
<p>As in the Traits paper, roles are composed at class construction
time, and the class composer does some work to make sure the composed
class is not unintentionally ambiguous.  If two methods of the same
name are composed into the same class, the ambiguity will be caught.
The author of the class has various remedies for dealing with this
situation, which we'll go into below.</p>
<p>From the standpoint of the typical user, a role just looks like a
&quot;smart&quot; include of a &quot;partial class&quot;.  They're smart in that roles
have to be well behaved in certain respects, but most of the time
the naive user can ignore the power of the abstraction.</p>
<a name='Declaration of Roles'></a><h2>Declaration of Roles</h2>
<p>A role is declared much like a class, but with a <code>role</code> keyword
instead:</p>
<pre>    role Pet {
	method feed ($food) {
	    $food.open_can();
	    $food.put_in_bowl();
	    .call();
	}
    }</pre>
<p>[Update: That'd have to be <code>self.call()</code> or <code>$.call()</code> these days.]</p>
<p>A role may not inherit from a class.  It may be composed of other
roles, however.  In essence, a role doesn't know its own type yet,
because it will be composed into another type.  So if you happen
to make any mention of its main type (available as <code>::_</code>),
that mention is in fact generic.  Therefore the type of
<code>$self</code> is generic.  Likewise if you refer to <code>SUPER</code>, the role doesn't
know what the parent classes are yet, so that's also generic.
The actual types are instantiated from the generic types when the
role is composed into the class.  (You can use the role name (&quot;<code>Pet</code>&quot;)
directly, but only in places where a role name is allowed as a type
constraint, not in places that declare the type of an actual object.)</p>
<p>[Update: Instead of <code>::_</code> we have <code>::?CLASS</code> to mean the generic
class.]</p>
<p>Just as the body of a class declaration is actually a method call
on an instance of the <code>MetaClass</code> class, so too the body of a role
declaration is actually a method call on an instance of the <code>MetaRole</code>
class, which is like the <code>MetaClass</code> class, with some tweaks to manage
<code>Role</code> objects instead of <code>Class</code> objects.  For instance, a <code>Role</code> object
doesn't actually support a dispatcher like a <code>Class</code> object.</p>
<p>[Update: Just as there's no <code>Class</code> type anymore, there's also no
<code>Role</code> type.  The metaobject handles everything type related (except
the name, which is a package name just like any other type).]</p>
<p><code>MetaRole</code> and <code>MetaClass</code> do not inherit from each other.  More likely
they both inherit from <code>MetaModule</code> or some such.</p>
<a name='Parametric types'></a><h3>Parametric types</h3>
<p>A role's main type is generic by default, but you can also parameterize
other types explicitly:</p>
<pre>    role Pet[Type $petfood = TableScraps] {
	method feed (::($petfood) $food) {...}
    }</pre>
<p>[Update: With type sigils that would just be</p>
<pre>    role Pet[::Petfood = TableScraps] {
	method feed (Petfood $food) {...}
    }</pre>
<p>now.]</p>
<p>Unlike certain other languages you may be altogether too familiar with,
Perl uses square brackets for parametric types rather than angles.
Within those square brackets it uses standard signature notation, so
you can also use the arguments to pass initial values, for instance.
Just bear in mind that by default any parameters to a role or class
are considered part of the name of the class when instantiated.
Inasmuch as instantiated type names are reminiscent of multimethod
&quot;long names&quot;, you may use a colon to separate those arguments that
are to be considered part of the name from those that are just options.</p>
<p>Please note that these types can be as latent (or as non-latent) as
you like.  Remember that what looks like compile time to you is actually
run time to the compiler, so it's free to bind types as early or late
as you tell it to, including not at all.</p>
<a name='Interfaces'></a><h3>Interfaces</h3>
<p>If a role merely declares methods without defining them, it degenerates
to an interface:</p>
<pre>    role Pet {
	method feed ($food) {...}
	method groom () {...}
	method scratch (+$where) {...}
    }</pre>
<p>When such a role is included in a class, the methods then have to be
defined by the class that uses the role.  Actually, each method is
on its own--a role is free to define default implementations for any
subset of the methods it declares.</p>
<a name='Private interfaces'></a><h3>Private interfaces</h3>
<p>If a role declares private accessors, those accessors are private
to the class, not the role.  The class must define any private
implementations that are not supplied by the role, just as with
public methods.  But private method names are never visible outside
the class (except to its trusted proxy classes).</p>
<p>[Update: See S12 for refinements of this.]</p>
<a name='Encapsulated Attributes'></a><h3>Encapsulated Attributes</h3>
<p>Unlike in the Traits paper, we allow roles to have state.  Which is fancy
way of saying that the role can define attributes, and methods that act on
those attributes, not just methods that act only on other methods.</p>
<pre>    role Pet {
	has $.collar = { Collar.new(Tag.new) };
	method id () { return $.collar.tag }
	method lose_collar () { undef $.collar }
    }</pre>
<p>By the way, I think that when <code>$.collar</code> is undefined, calling
<code>.tag</code> on it should merely return <code>undef</code> rather than throwing an
exception (in the same way that <code>@foo[$x][$y][$z]</code> returns <code>undef</code> when
<code>@foo[$x]</code> is undefined, and for the same reason).  The <code>undef</code>
object returned should, of course, contain an unthrown exception
documenting the problem, so that if the <code>undef</code> is ever asked to
provide a defined value, it can explain why it can't do so.  Or if
the returned value is tested by <code>//</code>, it can participate in the
resulting error message.</p>
<p>If you want to parameterize the initial value of a role attribute,
be sure to put a colon if you don't want the parameter to be considered
part of the long name:</p>
<pre>    role Pet[IDholder $id: $tag] {
	has IDholder $.collar .= new($tag);
    }
    class Dog does Pet[Collar, DogLicense(&quot;fido&quot;)] {...}
    class Pigeon does Pet[LegBand, RacerId()] {...}
    my $dog = new Dog;
    my $pigeon = new Pigeon;</pre>
<p>In which case the long names of the roles in question are <code>Pet[Collar]</code>
and <code>Pet[LegBand]</code>.  In which case all of these are true:</p>
<pre>    $dog.does(Dog)
    $dog.does(Pet)
    $dog.does(Pet[Collar])</pre>
<p>but this is false:</p>
<pre>    $dog.does(Pet[LegBand])</pre>
<p>Anyway, where were we.  Ah, yes, encapsulated attributes, which leads
us to...</p>
<a name='Encapsulated private attributes'></a><h3>Encapsulated private attributes</h3>
<p>We can also have private attributes:</p>
<pre>    has Nose $:sniffer .= new();</pre>
<p>[Update: That's <code>$!sniffer</code> now.]</p>
<p>And encapsulated private attributes lead us to...</p>
<a name='Encapsulated delegation'></a><h3>Encapsulated delegation</h3>
<p>A role can abstract the decision to delegate:</p>
<pre>    role Pet {
	has $:groomer handles «bathe groom trim» = hire_groomer();
    }</pre>
<p>Now when the <code>Dog</code> or <code>Cat</code> class incorporates the <code>Pet</code> role,
it doesn't even have to know that the <code>.groom</code> method is delegated
to a professional groomer.  (See section on Delegation below.)</p>
<a name='Encapsulated Inheritance'></a><h3>Encapsulated Inheritance</h3>
<p>It gets worse.  Since you can specify inheritance with an &quot;is&quot; declaration
within a class, you can do the same with a role:</p>
<pre>    role Pet {
	is Friend;
    }</pre>
<p>Note carefully that this is not claiming that a <code>Pet</code> ISA <code>Friend</code> (though
that might be true enough).  Roles never inherit.  So this is only
saying that whatever animal takes on the role of <code>Pet</code> gets some methods
from <code>Friend</code> that just happen to be implemented by inheritance rather
than by composition.  Probably <code>Friend</code> <i>should</i> have been written as
a role, but it wasn't (perhaps because it was written in Some Other
Language that runs on Parrot), and now you want to pretend that it
<i>was</i> written as a role to get your project out the door.  You don't
want to use delegation because there's only one animal involved,
and inheritance will work good enough till you can rewrite <code>Friend</code> in
a language that supports role playing.</p>
<p>Of course, the really funny thing is that if you go across a language
barrier like that, Perl might just decide to emulate the inheritance with
delegation anyway.  But that should be transparent to you.  And if two
languages manage to unify their object models within the Parrot engine,
you don't want to suddenly have to rewrite your roles and classes.</p>
<p>And the really, really funny thing is that Parrot implements roles
internally with a funny form of multiple inheritance anyway...</p>
<p>Ain't abstraction wonderful.</p>
<a name='Use of Roles at Compile Time'></a><h2>Use of Roles at Compile Time</h2>
<p>Roles are most useful at compile time, or more precisely, at class
composition time, the moment in which the <code>MetaClass</code> class is figuring
out how to put together your <code>Class</code> object.  Essentially, that's
while the closure associated with your class is being executed, with
a little extra happening before and after.</p>
<p>[Update: That should read &quot;put together your <code>MetaClass</code> object (and
the package associated with the name, if any)&quot;.]</p>
<p>A class incorporates a role with the verb &quot;does&quot;, like this:</p>
<pre>    class Dog is Mammal does Pet does Sentry {...}</pre>
<p>or equivalently, within the body of the class closure:</p>
<pre>    class Dog {
	is Mammal;
	does Pet;
	does Sentry;
	...
    }</pre>
<p>There is no ordering dependency among the roles, so it doesn't matter above
if <code>Sentry</code> comes before <code>Pet</code>.  That is because the class just remembers
all the roles and then meshes them after the closure is done executing.</p>
<p>Each role's methods are incorporated into the class unless there
is already a method of that name defined in the class itself.
A class's method definition hides any role definition of the same
name, so role methods are second-class citizens.  On the other hand,
role methods are still part of the class itself, so they hide any
methods inherited from other classes, which makes ordinary inherited
methods third-class citizens, as it were.</p>
<p>If there are no method name conflicts between roles (or with the
class), then each role's methods can be installed in the class,
and we're done.  (Unless we wish to do further analysis of role
interrelationships to make sure that each role can find the methods
it depends on, in which case we can do that.  But for 6.0.0 I'll be
happy if non-existent methods just fail at run time as they do now
in Perl 5.)</p>
<p>If, however, two roles try to introduce a method of the same name (for
some definition of name), then the composition of the class <i>fails</i>,
and the compilation of the program blows sky high--we sincerely hope.
It's much better to catch this kind of error at compile time if you can.
And in this case, you can.</p>
<a name='Conflict Resolution'></a><h3>Conflict Resolution</h3>
<p>There are several ways to solve conflicts.  The first is simply to
write a class method that overrides the conflicting role methods, perhaps
figuring out which role method to call.  It is allowed to use the role
name to select one of the hidden role methods:</p>
<pre>    method shake ($self: $arg) {
	given $arg {
	    when Culprit { $self.Sentry::shake($arg) }
	    when Paw     { $self.Pet::shake($arg) }
	}
    }</pre>
<p>So even though the methods were not officially composed into the class,
they're still there--they're not thrown away.</p>
<p>That last example looks an awful lot like multiple dispatch, and in fact,
if you declare the roles' methods with <code>multi</code>, they would be treated as
methods with different &quot;long names&quot;, provided their signatures were
sufficiently different.</p>
<p>An interesting question, though, is whether the class can force two
role methods that weren't declared &quot;multi&quot; to behave as if they were.
Perhaps this can be forced if the class declares a signatureless
multi stub without defining it later in the class:</p>
<pre>    multi shake {...}</pre>
<p>The Traits paper recommends providing ways of renaming or excluding one
or the other of the conflicting methods.  We don't recommend that, because
it's better if you can keep both contracts through multiple dispatch to
the role methods.  However, you can force renaming or exclusion by
pretending the role is a delegation:</p>
<pre>    does Pet handles [ :myshake«shake», Any ];
    does Pet handles { $^name !~ &quot;shake&quot; };</pre>
<p>Or something that.  (See the section on Delegation below.)  If we can't
get that to work right, you can always say something like:</p>
<pre>    method shake { .Sentry::shake(@_) }	   # exclude Pet::shake
    method handshake { .Pet::shake(@_) }   # rename Pet::shake</pre>
<p>In many ways that's clearer than trying to attach a selection syntax to
&quot;does&quot;.</p>
<p>[Update: That'd have to be self.Sentry etc. now.]</p>
<a name='Use of Roles at Run Time (mixins)'></a><h2>Use of Roles at Run Time (mixins)</h2>
<p>While roles are at their most powerful at compile time, they can also
function as mixin classes at run time.  The &quot;does&quot; binary operator
performs the feat of deriving a new class and binding the object to it:</p>
<pre>    $fido does Sentry</pre>
<p>Actually, it only does this if <code>$fido</code> doesn't already do the <code>Sentry</code>
role.  If it does already, this is basically a no-op.  The <code>does</code> operator
works on the object in place.  It would be illegal to say, for instance,</p>
<pre>    0 does true</pre>
<p>The <code>does</code> operator returns the object so you can nest mixins:</p>
<pre>    $fido does Sentry does Tricks does TailChasing does Scratch;</pre>
<p>Unlike the compile-time role composition, each of these layers on a new
mixin with a new level of inheritance, creating a new anonymous class
for dear old Fido, so that a <code>.chase</code> method from <code>TailChasing</code> hides a
<code>.chase</code> method from <code>Sentry</code>.</p>
<p>(Do not confuse the binary <code>does</code> with the unary <code>does</code> that you use
inside a class definition to pull in a role.)</p>
<p>In contrast to <code>does</code>, the <code>but</code> operator works on a copy.  So you can
say:</p>
<pre>    0 but true</pre>
<p>and you get a mixin based on a copy of 0, not the original 0, which
everyone shares.  One other wrinkle is that &quot;true&quot; isn't, in fact,
a class name.  It's an enumerated value of a bit class.  So what we
said was a shorthand for something like:</p>
<pre>    0 but bit::true</pre>
<p>[Update: That's <code>Bool::True</code> these days.]</p>
<p>In earlier Apocalypses we talked about applying properties with <code>but</code>.
This has now been unified with mixins, so any time you say:</p>
<pre>    $value but prop($x)</pre>
<p>you're really doing something more like</p>
<pre>    $tmp = $value;	# make a copy
    $tmp does SomeRole;	# guarantee there's a rw .prop method
    $tmp.prop = $x;	# set the prop method</pre>
<p>And therefore a property is defined by a role like this:</p>
<pre>    role SomeRole {
	has SomeType $.prop is rw = 1;
    }</pre>
<p>This means that when you mention &quot;<code>prop</code>&quot; in your program, something
has to know how to map that to the <code>SomeRole</code> role.  That would often be
something like an enum declaration.  It's illegal to use an undeclared
property.  But sometimes you just want a random old property for which
the role has the same name as the property.  You can declare one with</p>
<pre>    my property answer;</pre>
<p>and that essentially declares a role that looks something like</p>
<pre>    my role answer {
	has $.answer is rw = 1;
    }</pre>
<p>Then you can say</p>
<pre>    $a = 0 but answer(42)</pre>
<p>and you have an object of an anonymous type that &quot;does&quot; <code>answer</code>,
and that include a <code>.answer</code> accessor of the same name, so that if you
call <code>$a.answer</code>, you'll get back <code>42</code>.  But <code>$a</code> itself has the
value <code>0</code>.  Since the accessor is &quot;<code>rw</code>&quot;, you can also say</p>
<pre>    $a.answer = 43;</pre>
<p>There's a corresponding assignment operator:</p>
<pre>    $a but= tainted;</pre>
<p>That avoids copying <code>$a</code> before tainting it.  It basically means the
same thing as</p>
<pre>    $a does taint::tainted</pre>
<p>For more on enumerated types, see Enums below.</p>
<a name='Traits'></a><h1>Traits</h1>
<p>Here we're talking about Perl's traits (as in compile-time properties),
not Traits (as in the Traits paper).</p>
<p>Traits can be thought of as roles gone wrong.  Like roles, they can
function as straightforward mixins on container objects at compile
time, but they can also cheat, and frequently do.  Unlike roles,
traits are not constrained to play fair with each other.  With traits,
it's both &quot;first come, first served&quot;, and &quot;he who laughs last laughs
best&quot;.  Traits are applied one at a time to their container victim,
er, object, and an earlier trait can throw away information required
by a later trait.  Contrariwise, a later trait can overrule anything
done by an earlier trait--except of course that it can't undestroy
information that has been totally forgotten by the earlier trait.</p>
<p>You might say that &quot;role&quot; is short for &quot;role model&quot;, while &quot;trait&quot;
is short for &quot;traitor&quot;.  In a nutshell, roles are symbiotes, while
traits are parasites.  Nevertheless, some parasites are symbiotic,
and some symbiotes are parasitic.  Go figure...</p>
<p>All that being said, well-behaved traits are really just roles applied
to declared items like containers or classes.  It's the declaration of
the item itself that makes traits seem more permanent than ordinary
properties.  The only reason we call them &quot;traits&quot; rather than
&quot;properties&quot; is to continually remind people that they are, in fact,
applied at compile time.  (Well, and so that we can make bad puns on
&quot;traitor&quot;.)</p>
<p>Even ill-behaved traits should add an appropriately named role to
the container, however, in case someone wants to look at the metadata
properties of the container.</p>
<p>Traits are generally inflicted upon the &quot;traitee&quot; with the &quot;is&quot;
keyword, though other modalities are possible.  When the compiler
sees words like &quot;is&quot; or &quot;will&quot; or &quot;returns&quot; or &quot;handles&quot;, or
special constructs like signatures and body closures, it calls
into an associated trait handler which applies the role to the item
as a mixin, and also does any other traitorous magic that needs doing.</p>
<p>To define a trait handler for an &quot;is xxx&quot; trait, define one or
more multisubs into a property role like this:</p>
<pre>    role xxx {
	has Int $.xxx;
	multi sub trait_auxiliary:is(xxx $trait, Class $container: ?$arg) {...}
	multi sub trait_auxiliary:is(xxx $trait, Any $container: ?$arg) {...}
    }</pre>
<p>[Update: That's <code>trait_auxiliary:&lt;is&gt;</code> now.]</p>
<p>Then it can function as a trait.  A well-behaved trait handler will say</p>
<pre>    $container does xxx($arg);</pre>
<p>somewhere inside to set the metadata on the container correctly.  Then
not only can you say</p>
<pre>    class MyClass is xxx(123) {...}</pre>
<p>but you'll also be able to say</p>
<pre>    if MyClass.meta.xxx == 123 {...}</pre>
<p>Since a class can function as a role when it comes to parameter type
matching, you can also say:</p>
<pre>    class MyBase {
	multi sub trait_auxiliary:is(MyBase $base, Class $class: ?$arg) {...}
	multi sub trait_auxiliary:is(MyBase $tied, Any $container: ?$arg) {...}
    }</pre>
<p>These capture control if <code>MyBase</code> wants to capture control of how it gets
used by any class or container.  But usually you can just let it call
the generic defaults:</p>
<pre>    multi sub *trait_auxiliary:is(Class $base, Class $class: ?$arg) {...}</pre>
<p>which adds <code>$base</code> to the &quot;isa&quot; list of <code>$class</code>, or</p>
<pre>    multi sub *trait_auxiliary:is(Class $tied, Any $container: ?$arg) {...}</pre>
<p>which sets the &quot;tie&quot; type of the container to the implementation type
in <code>$tied</code>.</p>
<p>In any event, if the trait supplies the optional argument, that
comes in as <code>$arg</code>.  (It's probably something unimportant, like the
function body...)  Note that unlike &quot;pair options&quot; such as &quot;<code>:wag</code>&quot;,
traits do not necessarily default to the value 1 if you don't supply
the argument.  This is consistent with the notion that traits don't
generally do something passive like setting a value somewhere,
but something active like totally screwing up the structure of your
container.</p>
<p>Most traits are introduced by use of a &quot;helping verb&quot;, which could
be something like &quot;<code>is</code>&quot;, or &quot;<code>will</code>&quot;, or &quot;<code>can</code>&quot;, or &quot;<code>might</code>&quot;, or &quot;<code>should</code>&quot;,
or &quot;<code>does</code>&quot;.  We call these helping verbs &quot;trait auxiliaries&quot;. Here's
&quot;<code>will</code>&quot;, which (being syntactic sugar) merely delegates to back to &quot;is&quot;:</p>
<pre>    multi sub *trait_auxiliary:will($trait, $container: &amp;arg) {
	trait_auxiliary:is($trait, $container, &amp;arg);
    }</pre>
<p>Note the declaration of the argument as a non-optional reference to
a closure.  This is what allows us to say:</p>
<pre>    my $dog will eat { anything() };</pre>
<p>rather than having to use parens:</p>
<pre>    my $dog is eat({ anything() });</pre>
<p>Other traits are applied with a single word, and we call one of those a
&quot;trait verb&quot;.  For instance, the &quot;<code>returns</code>&quot; trait described in
Apocalypse 6 is defined something like this:</p>
<pre>    role returns {
	has ReturnType $.returns;
	multi sub trait_verb:returns($container: ReturnType $arg) {
	    $container does returns($arg);
	}
	...
    }</pre>
<p>[Update: Make that <code>trait_verb:&lt;returns&gt;</code> now.]</p>
<p>Note that the argument is not optional on &quot;<code>returns</code>&quot;.</p>
<p>Earlier we defined the <code>xxx</code> trait using multi sub definitions:</p>
<pre>    role xxx {
	has Int $.xxx;
	multi sub trait_auxiliary:is(xxx $trait, Class $container: ?$arg) {...}
	multi sub trait_auxiliary:is(xxx $trait, Any $container: ?$arg) {...}
    }</pre>
<p>This is one of those situations in which you may really want
single-dispatch methods:</p>
<pre>    role xxx {
	has Int $.xxx;
	method trait_auxiliary:is(xxx $trait: Class $container, ?$arg) {...}
	method trait_auxiliary:is(xxx $trait: Any $container, ?$arg) {...}
    }</pre>
<p>Some traits are control freaks, so they want to make sure that anything
mentioning them comes through their control.  They don't want something
dispatching to another trait's <code>trait_auxiliary:is</code> method just because
someone introduced a cute new container type they don't know about.
That other trait would just mess things up.</p>
<p>Of course, if a trait is feeling magnanimous, it should just go ahead
and use multi subs.  Since the multi-dispatcher takes into account
single-dispatch methods, and the distance of an exact match on the
first argument is 0, the dispatcher will generally respect the wishes
of both the paranoid and the carefree.</p>
<p>Note that we included &quot;does&quot; in our list of &quot;helping verbs&quot;.
Roles actually implement themselves using the trait interface, but the
generic version of <code>trait_auxiliary:does</code> defaults to doing proper roley
things rather than proper classy things or improper traitorous things.
So yes, you could define your own <code>trait_auxiliary:does</code> and turn your
nice role traitorous.  That would be...naughty.</p>
<p>But apart from how you typically invoke them, traits and roles are
really the same thing.  Just like the roles on which they're based,
you may neither instantiate nor inherit from a trait.  You may,
however, use their names as type constraints on multimethod signatures
and such.  As with well-behaved roles, they should define attributes or
methods that show up as metadata properties where that's appropriate.
Unlike compile-time roles, which all flatten out in the same class,
compile-time traits are applied one at a time, like mixin roles.
You can, in fact, apply a trait to a container at run time, but
if you do, it's just an ordinary mixin role. You have to call the
appropriate <code>trait_auxiliary:is()</code> routine yourself if you want it to
do any extra shenanigans.  The compiler won't call it for you at run
time like it would at compile time.</p>
<p>When you define a helping verb such as &quot;is&quot; or &quot;does&quot;, it not only
makes it a postfix operator for declarations, but a unary operator
within class and role closures.  Likewise, declarative closure blocks
like <code>BEGIN</code> and <code>INIT</code> are actually trait verbs, albeit ones that can
add multiple closures to a queue rather than adding a single property.
This implies that something like</p>
<pre>    sub foo {
	LEAVE {...}
	...
    }</pre>
<p>could (except for scoping issues) equivalently be written:</p>
<pre>    sub foo LEAVE {...} {
	...
    }</pre>
<p>Though why you'd want to that, I don't know.  Hmm, if we really generalize
trait verbs like that, then you could also write things like:</p>
<pre>    sub foo {
	is signature ('int $x');
	is cached;
	returns Int;
	...
    }</pre>
<p>That's gettin' a little out there.  Maybe we won't generalize it
quite that far...</p>
<a name='Delegation'></a><h1>Delegation</h1>
<p>Delegation is the art of letting someone else do your work for you.
The fact that you consider it &quot;your&quot; work implies that delegation is
actually a means of taking credit in advance for what someone else is
going to do.  In terms of objects, it means pretending that some other
object's methods are your own.  Now, as it happens, you can always
do that by hand simply by writing your own methods that call out to
another object's methods of the same name.  So any shorthand for doing
that is pure syntactic sugar.  That's what we're talking about here.</p>
<p>Delegation in this sugary sense always requires there to be an
attribute to keep a reference to the object we're delegating to.
So our syntactic relief will come in the form of annotations on a
&quot;<code>has</code>&quot; declaration.  We could have decided to instead attach annotations
to each method declaration associated with the attribute, but by the
time you do this, you've repeated so much information that you almost
might as well have written the non-sugary version yourself.  I know
that for a fact, because that's how I originally proposed it.  <code>:-)</code></p>
<p>Delegation is specified by a &quot;handles&quot; trait verb with an argument
specifying one or more method names that the current object and the
delegated object will have in common:</p>
<pre>    has $:tail handles 'wag';</pre>
<p>Since the method name (but nothing else) is known at class construction
time, the following <code>.wag</code> method is autogenerated for you:</p>
<pre>    method wag (*@args is context(Lazy)) { $:tail.wag(*@args) }</pre>
<p>(It's necessary to specify a <code>Lazy</code> context for the arguments to a such a
delegator method because the actual signature is supplied by the tail's
<code>.wag</code> method, not your method.)</p>
<p>[Update: Now you use Captures:</p>
<pre>    method wag (\$args) { $!tail.wag([,]$args) }</pre>
<p>]</p>
<p>So as you can see, the delegation
syntax already cuts our typing in half, not to mention the reading.
The win is even greater when you specify multiple methods to delegate:</p>
<pre>    has $:legs handles «walk run lope shake pee»;</pre>
<p>Or equivalently:</p>
<pre>    has $:legs handles ['walk', 'run', 'lope', 'shake', 'pee'];</pre>
<p>You can also say things like</p>
<pre>    my @legmethods := «walk run lope shake pee»;
    has $:legs handles (@legmethods);</pre>
<p>since the &quot;<code>has</code>&quot; declaration is evaluated at class construction time.</p>
<p>Of course, it's illegal to call the outer method unless the attribute
has been initialized to an object of a type supporting the method.
So a declaration that makes a new delegatee at object build time
might be specified like this:</p>
<pre>    has $:tail handles 'wag' will build { Tail.new(*%_) };</pre>
<p>or, equivalently,</p>
<pre>    has $:tail handles 'wag' = { Tail.new(*%_) };</pre>
<p>This automatically performs</p>
<pre>    $:tail = Tail.new(*%_);</pre>
<p>when <code>BUILD</code> is called on a new object of the current class (unless
<code>BUILD</code> initializes <code>$:tail</code> to some other value).  Or, since you
might want to declare the type of the attribute without duplicating
it in the default value, you can also say</p>
<pre>    has Tail $:tail handles 'wag' = { .new(*%_) };</pre>
<p>or</p>
<pre>    has Tail $:tail handles 'wag' will build { .new(*%_) };</pre>
<p>Note that putting a <code>Tail</code> type on the attribute does not necessarily
mean that the method is always delegated to the <code>Tail</code> class.
The dispatch is still based on the <i>run-time</i> type of the object,
not the declared type.  So</p>
<pre>    has Tail $:tail handles 'wag' = { LongTail.new(*%_) };</pre>
<p>delegates to the <code>LongTail</code> class, not the <code>Tail</code> class.  Of course, you'll
get an exception at build time if you try to say:</p>
<pre>    has Tail $:tail handles 'wag' = { Dog.new(*%_) };</pre>
<p>since <code>Dog</code> is not derived from <code>Tail</code> (whether or not the tail can wag
the dog).</p>
<p>We declare <code>$:tail</code> as a private attribute here, but <code>$.tail</code> would
have worked just as well.  A <code>Dog</code>'s tail does seem to be a public
interface, after all.  Kind of a read-only accessor.</p>
<a name='Wildcard Delegation'></a><h2>Wildcard Delegation</h2>
<p>We've seen that the argument to &quot;<code>handles</code>&quot; can be a string or a list
of strings.  But any argument or subargument that is not a string is
considered to be a smartmatch selector for methods.  So you can say:</p>
<pre>    has $:fur handles /^get_/;</pre>
<p>and then you can do the <code>.get_wet</code> or <code>.get_fleas</code> methods (presuming
there are such), but you can't call the <code>.shake</code> or <code>.roll_in_the_dirt</code>
methods.  (Obviously you don't want to delegate the <code>.shake</code> method since
that means something else when applied to the <code>Dog</code> as a whole.)</p>
<p>If you say</p>
<pre>    has $:fur handles Groomable;</pre>
<p>then you get only those methods available via the <code>Groomable</code> role
or class.</p>
<p>Wildcard matches are evaluated only after it has been determined that
there's no exact match to the method name.  They therefore function
as a kind of autoloading in the overall pecking order.  If the class
also has an <code>AUTOLOAD</code>, it is called only if none of the wildcard
delegations match.  (An <code>AUTOMETHDEF</code> is called much earlier, since it
knows from the stub declarations whether there is supposed to be a
method of that name.  So you can think of explicit delegation as a
kind of autodefine, and wildcard delegation as a kind of autoload.)</p>
<p>When you have multiple wildcard delegations to different objects,
it's possible to have a conflict of method names.  Wildcard method
matches are evaluated in order, so the earliest one wins.  (Non-wildcard
method conflicts can be caught at class composition time.)</p>
<a name='Renaming Delegated Methods'></a><h2>Renaming Delegated Methods</h2>
<p>If, where you would ordinarily specify a string, you put a pair, then
the pair maps the method name in this class to the method name in the
other class.  If you put a hash, each key/value pair is treated as
such a mapping.  Such mappings are not considered wildcards.</p>
<pre>    has $:fur handles { :shakefur«shake» :scratch«get_fleas» };</pre>
<p>Perhaps that reads better with the old pair notation:</p>
<pre>    has $:fur handles { shakefur =&gt; 'shake', scratch =&gt; 'get_fleas' };</pre>
<p>You <i>can</i> do a wildcard renaming, but not with pairs.  Instead do smartmatch
with a substitution:</p>
<pre>    has $:fur handles (s/^furget_/get_/);</pre>
<p>As always, the left-to-right mapping is from this class to the other one.
The pattern matching is working on the method name passed to us, and
the substituted method name is used on the class we delegate to.</p>
<a name='Delegation without an Attribute'></a><h2>Delegation without an Attribute</h2>
<p>Ordinarily delegation is based on an attribute holding an object
reference, but there's no reason in principle why you have to use an
attribute.  Suppose you had a <code>Dog</code> with two tails.  You can delegate
based on a method call:</p>
<pre>    method select_tail handles «wag hang» {...}</pre>
<p>The arguments are sent to both the delegator and delegatee method.
So when you call</p>
<pre>    $dog.wag(:fast)</pre>
<p>you're actually calling</p>
<pre>    $dog.select_tail(:fast).wag(:fast)</pre>
<p>If you use a wildcard delegation based on a method, you should be
aware that it has to call the method before it can even decide whether
there's a valid method call to the delegatee or not.  So it behooves
you not to get too fancy with <code>select_tail()</code>, since it might just have
to throw all that work away and go on to the next wildcard specification.</p>
<a name='Delegation of Handlers'></a><h2>Delegation of Handlers</h2>
<p>If your delegation object happens to be an array:</p>
<pre>    has @:handlers handles 'foo';</pre>
<p>then something cool happens.  &lt;cool rays&gt;  In this case Perl 6
assumes that your array contains a list of potential handlers, and you
just want to call the <i>first</i> one that succeeds.  This is not considered
a wildcard match unless the &quot;handles&quot; argument forces it to be.</p>
<p>Note that this is different from the semantics of a hyper method such
as <code>@objects».foo()</code>, which will try to call the method on <i>every</i>
object in <code>@objects</code>.  If you want to do that, you'll just have to
write your own method:</p>
<pre>    has @:ears;
    method twitchears () { @:ears».twitch() }</pre>
<p>Life is hard.</p>
<a name='Hash-Based Redispatch'></a><h2>Hash-Based Redispatch</h2>
<p>If your delegation object happens to be a hash:</p>
<pre>    has %:objects handles 'foo';</pre>
<p>then the hash provides a mapping from the string value of &quot;self&quot;
to the object that should be delegated to:</p>
<pre>    has %:barkers handles &quot;bark&quot; =
		(Chihauhau =&gt; $yip,
		    Beagle =&gt; $yap,
		   Terrier =&gt; $arf,
		 StBernard =&gt; $woof,
		);
    method prefix:~( return &quot;$.breed&quot; )</pre>
<p>[Update: That's <code>prefix:&lt;~&gt;</code> now.]</p>
<p>If the string is not found in the hash, a &quot;<code>next METHOD</code>&quot; is
automatically performed.</p>
<p>Again, this construct is not necessarily considered a wildcard.
In the example above we know for a fact that there's supposed to
be a <code>.bark</code> method somewhere, therefore a specific method can be
autogenerated in the current class.</p>
<a name='Relationship to Roles'></a><h2>Relationship to Roles</h2>
<p>Delegation is a means of including a set of methods into your class.
Roles can also include a set of methods in your class, but the difference
is that what a role includes happens at class composition time, while
delegation is much more dynamic, depending on the current state of the
the delegating attribute (or method).</p>
<p>But there's no reason you can't have your cake and eat it too, because
roles are specifically designed to allow you to pull in delegations
without the class even being aware of the fact that it's delegating.
When you include a role, you're just signing up for a set of methods,
with maybe a little state thrown in.  You don't care whether those
methods are defined directly, or indirectly.  The role manages that.</p>
<p>In fact, this is one of the primary motivators for including roles
in the design of Perl 6.  As a named abstraction, a role lets you
refactor all the classes using that role without changing any of the
classes involved.  You can turn your single &quot;god&quot; object into a set
of nicely cooperating objects transparently.  Well, you have to do
the composition using roles first, and that's not transparent.</p>
<p>Note that all statically named methods are dispatched before any
wildcard methods, regardless of whether the methods came from a role
or the class itself.  (Inherited methods also come before wildcard
methods because we order all the cachable method dispatches before
all the non-cachable ones.  But see below.)  So the lookup order is:</p>
<ul>
<li><a name='1.'></a>1.</li>
<p>This class's declared methods (including autodefs and delegations)</p>
<li><a name='2.'></a>2.</li>
<p>An included role's declared methods (including autodefs and delegations)</p>
<li><a name='3.'></a>3.</li>
<p>Normal inherited methods (including autodefs and delegations
of the parent class)</p>
<li><a name='4.'></a>4.</li>
<p>Wildcard delegated methods in this class (or failing that, from any
inherited class that does wildcard delegations)</p>
<li><a name='5.'></a>5.</li>
<p>Methods autoloaded by an autoloader defined in this class (or failing
that, an autoloader from any inherited class)</p>
</ul>
<p>Note that any method that is stubbed (declared but not yet defined)
in steps 1 or 2 skips straight to step 4, because it means this
class thinks it &quot;owns&quot; a method of that name.  (At this point Perl 5
would skip straight to step 5, but Perl 6 still wants to do wildcard
delegation before falling back on inherited autoloading.)</p>
<a name='Anonymous Delegation for ISA Emulation'></a><h2>Anonymous Delegation for ISA Emulation</h2>
<p>When you inherit from a class with a different layout policy, Perl has
to emulate inheritance via anonymous delegation.  In this case it
installs a wildcard delegation for you.  According to the list above,
this gives precedence to all methods with the same layout policy over
all methods with a different layout policy.  This might be a feature,
especially when calling cross-language.  Then again, maybe it isn't.</p>
<p>There is no &quot;<code>has</code>&quot; variable for such an anonymous delegation.  Its
delegated object is stored as a property on the class's entry
in the ISA list, probably.  (Or we could autogenerate an attribute
whose name is related to the class name, I suppose.)</p>
<p>Since one of the primary motivations for allowing this is to make it
possible to call back and forth between Perl 5 and Perl 6 objects,
we need to make that as transparent as possible.  When a Perl 6
object inherits from a Perl 5 object, it is emulated with delegation.
The invocant passed into the Perl 5 (Ponie) object looks like a Perl
5 object to Perl 5.  However, if the Perl 5 object passes that as an
invocant back into Perl 6, it has to go back to looking like a Perl
6 object to Perl 6, or our emulation of inheritance is suboptimal.
When a Ponie object accesses its attributes through what it <i>thinks</i>
is a hash reference, it really has to call the appropriate Perl 6
accessor function if the object comes from Perl 6.  Likewise, when
Perl 6 calls an accessor on a Perl 5 object, it has to translate that
method call into a hash lookup--presuming that the Perl 5 object is
implemented as a blessed hash.</p>
<p>Other language boundaries may or may not do similar tricks.  Python's
attributes suffer from the same misdesign as Perl 5's attributes.  (My
fault for copying Python's object model. <code>:-)</code>  So that'd be a good place
for a similar policy.</p>
<p>So we can almost certainly emulate inheritance with delegation,
albeit with some possible misordering of classes if there are duplicate
method names.  However, the hard part is constructing objects.  Perl 5
doesn't enforce a policy of named arguments for its constructors, so
it is difficult for a Perl 6 <code>BUILDALL</code> routine to have any automatic
way to call a Perl 5 constructor.  It's tempting to install glue code
into the Perl 6 class that will do the translation, but that's really
not a good idea, because someday the Perl 5 class may eventually get
translated to a Perl 6 class, and your glue code will be useless,
or worse.</p>
<p>So the right place to put the glue is actually back into the Perl
5 class.  If a Perl 5 class defines a <code>BUILD</code> subroutine, it will
be assumed that it properly handles named pairs in Perl 5's even/odd
list format.  That will be used in lieu of any predefined constructor
named &quot;<code>new</code>&quot; or anything else.</p>
<p>If there is no <code>BUILD</code> routine in the Perl 5 package, but there is
a &quot;<code>use fields</code>&quot; declaration, then we can autogenerate a rudimentary
<code>BUILD</code> routine that should suffice for most scalar attributes.</p>
<a name='Types and Subtypes'></a><h1>Types and Subtypes</h1>
<p>I've always really liked the Ada distinction between types and
subtypes.  A type is something that adds capabilities, while a
subtype is something that takes away capabilities.  Classes and
roles generally function as types in Perl 6.  In general you don't
want to make a subclass that, say, restricts your integers to only
even numbers, because then you've violated Liskov substitutability.
In the same way that we force role composition to be &quot;before&quot; classes,
we will force subtyping constraints to be &quot;after&quot; classes.  In both
cases we force it by a declarator change so that you are unlikely
to confuse a role with a class, or a class with a subtype.  And just
as you aren't allowed to derive a role from a class, you aren't
allowed to derive a class from a constrained type.</p>
<p>On the other hand, a bit confusingly, it looks like subtyping will
be done with the &quot;type&quot; keyword, since we aren't using that word yet.</p>
<p>To remind people that a subtype of a class is just a constrained alias
for the class, we avoid the &quot;is&quot; word and declare a type using a <code>::=</code>
compile-time alias, like this:</p>
<pre>    type Str_not2b ::= Str where /^[isnt|arent|amnot|aint]$/;</pre>
<p>The <code>::=</code> doesn't create the type, nor in fact does the <code>type</code>
keyword.  It's actually the <code>where</code> that creates the type.  The <code>type</code>
keyword just marks the name as &quot;not really a classname&quot; so that you
don't accidentally try to derive from it.</p>
<p>[Update: I decided I don't like the forced use of <code>::=</code>, nor do I
like the confusion engendered by use the word &quot;type&quot; to mean &quot;subtype&quot;,
so the syntax is now any of:</p>
<pre>    my subset Str_not2b of Str where /^[isnt|arent|amnot|aint]$/;
    my Str subset Str_not2b where /^[isnt|arent|amnot|aint]$/;</pre>
<p>.]</p>
<p>Since a type is &quot;post-class-ical&quot;, there's really no such thing as an
object blessed into a type.  If you try it, you'll just end up with
an object blessed into whatever the underlying unconstrained class
is, as far as inheritance is concerned.  A type is not a subclass.
A type is primarily a handy way of sneaking smartmatching into
multiple dispatch.  Just as a role allows you to specify something
more general than a class, a type allows you to specify something
more specific than a class.</p>
<p>While types are primarily intended for restricting parameter types
for multiple dispatch, they also let you impose preconditions on
assignment.  Basically, if you declare any container with a subtype,
Perl will check the constraint against any value you might try to
bind or assign to the container.</p>
<pre>    type Str_not2b ::= Str where /^[isnt|arent|amnot|aint]$/;
    type EvenNum   ::= Num where { $^n % 2 == 0 }

    my Str_not2b $hamlet;
    $hamlet = 'isnt';   # Okay because 'isnt' ~~ /^[isnt|arent|amnot|aint]$/
    $hamlet = 'amnt';   # Bzzzzzzzt!   'amnt' !~ /^[isnt|arent|amnot|aint]$/

    my EvenNum $n;
    $n = 2;             # Okay
    $n = -2;            # Okay
    $n = 0;             # Okay
    $n = 3;             # Bzzzzzzzt</pre>
<p>It's perfectly legal to base one subtype on another.  It merely
adds an additional constraint.</p>
<p>It's possible to use an anonymous subtype in a signature:</p>
<pre>    use Rules::Common :profanity;

    multi sub mesg (Str where /&lt;profanity&gt;/ $mesg is copy) {
	$mesg ~~ s:g/&lt;profanity&gt;/[expletive deleted]/;
	print $MESG_LOG: $mesg;
    }

    multi sub mesg (Str $mesg) {
	print $MESG_LOG: $mesg;
    }</pre>
<p>Given a set of multimethods that would &quot;tie&quot; on the actual classes
of the arguments, a multimethod with a matching constraint will be
preferred over an equivalent one with no constraint.  So the first
<code>mesg</code> above is preferred if the constraint matches, and otherwise
the second is preferred.  However, if two multis with constraints
match (and are otherwise equivalent), it's just as if you'd called
any other set of ambiguous multimethods, and one of them had better
be marked as the default, or you die.</p>
<p>We say that types are &quot;post-class-ical&quot;, but since you can base them off
of any class including <code>Any</code>, they are actually rather orthogonal to
the class system.</p>
<p>[Update: Everywhere the preceding section says &quot;type&quot;, change to &quot;subtype&quot;,
except for the keyword, which changes to &quot;subset&quot;.  And change <code>::=</code> to <code>of</code>.]</p>
<a name='Enums'></a><h1>Enums</h1>
<p>An enum functions as a subtype that is constrained to a single value.
(When a subtype is constrained to a single value, it can be used for that
value.)  But rather than declaring it as:</p>
<pre>    type DayOfWeek ::= Int where 0..6;
    type DayOfWeek::Sunday    ::= DayOfWeek where 0;
    type DayOfWeek::Monday    ::= DayOfWeek where 1;
    type DayOfWeek::Tuesday   ::= DayOfWeek where 2;
    type DayOfWeek::Wednesday ::= DayOfWeek where 3;
    type DayOfWeek::Thursday  ::= DayOfWeek where 4;
    type DayOfWeek::Friday    ::= DayOfWeek where 5;
    type DayOfWeek::Saturday  ::= DayOfWeek where 6;</pre>
<p>we allow a shorthand:</p>
<pre>    type DayOfWeek ::= int enum
	«Sunday Monday Tuesday Wednesday Thursday Friday Saturday»;</pre>
<p>[Update: The syntax is now more like existing declarations:</p>
<pre>    our int enum DayOfWeek
	&lt;Sunday Monday Tuesday Wednesday Thursday Friday Saturday&gt;;</pre>
<p>where <code>int</code> is usually omitted.]</p>
<p>Type <code>int</code> is the default enum type, so that can be:</p>
<pre>    type DayOfWeek ::= enum
	«Sunday Monday Tuesday Wednesday Thursday Friday Saturday»;</pre>
<p>[Update: Now just <code>enum DayOfWeek &lt;...&gt;</code>.]</p>
<p>The enum installer inspects the strings you give it for things that
look like pairs, so to number your days from 1 to 7, you can say:</p>
<pre>    type DayOfWeek ::= enum
	«:Sunday(1) Monday Tuesday Wednesday Thursday Friday Saturday»;</pre>
<p>You can import individual enums into your scope where they will
function like argumentless constant subs.  However, if there is a
name collision with a sub or other enum, you'll have to disambiguate.
Unambiguous enums may be used as a property on the right side of a &quot;but&quot;,
and the enum type can be intuited from it to make sure the object in
question has the right semantics mixed in.  Two builtin enums are:</p>
<pre>    type bool ::= bit enum «false true»;
    type taint ::= bit enum «untainted tainted»;</pre>
<p>[Update: Now just:</p>
<pre>    our bit enum *Bool is &lt;False True&gt;;
    our bit enum *Taint is &lt;Untainted Tainted&gt;;</pre>
<p>.]</p>
<a name='Open vs Closed Classes'></a><h1>Open vs Closed Classes</h1>
<p>By default, classes in Perl are left open.  That is, you can add
more methods to them, though you have to be explicit that that is
what you're doing:</p>
<pre>    class Object is extended {
	method wow () { say &quot;Wow, I'm an object.&quot; }
    }</pre>
<p>Otherwise you'll get a class redefinition error.</p>
<p>Likewise, a &quot;final&quot; class (to use the Java term) is one that you know
will never be derived from, let alone mucked with internally.</p>
<p>Now, it so happens that leaving all your classes open is not terribly
conducive to certain kinds of optimization (let alone encapsulation).
From the standpoint of the compiler, you'd like to be able to say,
&quot;I know this class will never be derived from or modified, so I can
do things like access my attributes directly without going through
virtual accessors.&quot;  We were, in fact, tempted to make closed classes
the default.  But this breaks in frameworks like mod_perl where you
cannot predict in advance which classes will want to be extended or
derived from.</p>
<p>Some languages solve this (or think they solve it) by letting classes
declare themselves to be closed and/or final.  But that's actually
a bad violation of OO principles.  It should be the <i>users</i> of a class
that decide such things--and decide it for themselves, not for others.
As such, there has to be a consensus among all users of a class to
close or finalize it.  And as we all know, consensus is difficult
to achieve.</p>
<p>Nevertheless, the Perl 6 approach is to give the top-level application
the right to close (and finalize) classes.  But we don't do this by
simply listing the classes we want to close.  Instead, we use the
sneaky strategy of switching the default to closed and then list the
classes we want to stay open.</p>
<p>The benefit of this is that modules other than the top level can
simply list all the classes that they know should stay open.  In an
open framework, these are, at worst, no-ops, and they don't cause
classes to close that other modules might want to remain open.
If <i>any</i> module requests a class to stay open, it stays open.
If <i>any</i> module requests that a class remain available as a base
class, it remains available.</p>
<p>It has been speculated that optimizer technology in Parrot will
develop such that a class can conjecturally be compiled as closed,
and then recompiled as open should the need arise.  (This is just
a specific case of the more general problem of what you do whenever
the assumptions of the optimizer are violated.)  If we get such an
on-the-fly optimizer/pessimizer, then our open class declarations are
still not wasted--they will tell the optimizer which classes not to
bother trying to close or finalize in the first place.  Setting the
default the other way wouldn't have the same benefit.</p>
<p>Syntax?  You want syntax?  Hmm.</p>
<pre>    use classes :closed :open«Mammal Insect»;</pre>
<p>[Update: Now more like &quot;<code>use opt :classes(:close :finalize);</code>&quot;, since
it's direct instruction to the optimizer.  It doesn't directly change
the meaning of the <code>class</code> keyword, so it shouldn't use <code>class</code>
as the pragma name.]</p>
<p>Or some such.  Maybe certain kinds of class reference automatically request
the class to be open without a special pragma.  A module could request
open classes without attempting to close everything with just:</p>
<pre>    use classes :open«Mammal Insect»;</pre>
<p>[Update: Just &quot;<code>class</code>&quot; to match the keyword.]</p>
<p>On the other hand, maybe that's another one of those inside-out interfaces,
and it should just be options on the classes whose declarations you have
to include anyway:</p>
<pre>    use classes :closed;
    class Mammal is open {...}
    class Insect is open {...}</pre>
<p>Similarly, we can finalize classes by default and then &quot;take it back&quot;
for certain classes:</p>
<pre>    use classes :final;
    class Mammal is base {...}
    class Insect is base {...}</pre>
<p>In any event, even though the default is expressed at the top of the
main application, the final decision on each class is not made by
the compiler until <code>CHECK</code> time, when all the compiled code has had
a chance to stake its claims.  (A JIT compiler might well wait even
longer, in case run-time evaluated code wishes to express an opinion.)</p>
<a name='Interface Consistency'></a><h1>Interface Consistency</h1>
<p>In theory, a subclass should always act as a more specialized version
of a superclass.  In terms of design-by-contract theory, a subclass
should OR in its preconditions and AND in its postconditions.  In terms
of Liskov substitutability, you should always be able to substitute
a derived class object in where a base class object is expected, and
not have it blow up.  In terms of Internet policy, a derived class
(compared to its base class) should be at least as lenient in what it
accepts, and at least as strict in what it emits.</p>
<p>So, while it would be lovely in a way to require that derived methods
of the same name as a base method must use the same signature, in
practice that doesn't work out.  A derived class often has to be
able to add arguments to the signature of a method so that it can
&quot;be more lenient&quot; in what it accepts as input.</p>
<p>But this poses a problem, insofar as the user of the derived object
does not know whether all the methods of a given name support the
same interface.  Under <code>SUPER</code> semantics, one can at least assume
that the derived class will &quot;weed out&quot; any arguments that would be
detrimental to its superclass.  But as we have already pointed out,
there isn't a single superclass under MI, and each superclass might
need to have different &quot;detrimental arguments&quot; weeded out.  One could
say that in that case, you don't call <code>SUPER</code> but rather call out to
each superclass explicitly.  But then you're back to the problem that
<code>SUPER</code> was designed to solve.  And you haven't solved <code>SUPER</code>'s
problem either.</p>
<p>Under <code>NEXT</code> semantics, we assume that we are dispatching to a set
of methods with the same name, but potentially different signatures.
(Perl 6's <code>SUPER</code> implementation is really a limited form of <code>NEXT</code>,
insofar as <code>SUPER</code> indicates a set of parent methods, unlike in
Perl 5 where it picks one.)  We need a way of satisfying different
signatures with the same set of arguments.</p>
<p>There are, in fact, two ways to approach this.  One way is to say,
okay everything is a multimethod, and we just won't call anything
whose signature is irreconcilably inconsistent with the arguments
presented.  Plus there are varying degrees of consistency within the
set of &quot;consistent&quot; interfaces, so we try them in decreasing order
of consistency.  A more consistent multi is allowed to fall back to
a less consistent multi with &quot;<code>next METHOD</code>&quot;.</p>
<p>But as a variant of the &quot;pick one&quot; mentality, that still doesn't
help the situation where you want to send a message to all your
ancestor classes (like &quot;Please Mr. Base Class, help me initialize
this object.&quot;), but you want to be more specific with some classes
than others (&quot;Please Miss Derived Class, set your <code>$.prim</code> attribute
to 1.&quot;).  So the other approach is to use named arguments that can
be ignored by any classes that don't grok the argument.</p>
<p>So what this essentially comes down to is the fact that all methods and
submethods of classes that might be derived from (which is essentially
all classes, but see the previous section) must have a <code>*%</code> parameter,
either explicitly or implicitly, to collect up and render harmless
any unrecognized option pairs in the argument list.  So the ruling
is that all methods and submethods that do not declare an explicit
<code>*%</code> parameter will get an implicit <code>*%_</code> parameter declared for them
whether they like it or not.  (Subroutines are not granted this &quot;favor&quot;.)</p>
<p>It might be objected that this will slow down the parameter binding
algorithm for all methods favored with an implicit <code>*%_</code>, but I would
argue that the binding code doesn't have to do anything till it sees
a named parameter it doesn't recognize, and then it can figure out
whether the method even references <code>%_</code>, and if not, simply throw the
unrecognized argument away instead of constructing a <code>%_</code> that won't
be used.  And most of this &quot;figuring out&quot; can be done at compile time.</p>
<p>Another counterargument is that this prevents a class from recognizing
typos in argument names.  That's true.  It might be possible to ask
for a warning that checks globally (at class-finalization time in
the optimizer?) to see if there is any method of that name anywhere that
is interested in a parameter of that name.  But any class that
gets its parameters out of a <code>*%</code> hash at run time would cause false
positives, unless we assume that any <code>*%</code> hash makes any argument name
legal, in which case we're pretty much back to where we started, unless
we do analysis of the usage of all <code>*%</code> hash in those methods, and count
things like <code>%_«prim»</code> as proper parameter declarations.  And that
can still be spoofed in any number of ways.  Plus it's not a trivial
warning to calculate, so it probably wouldn't be the default in a
load-and-go interpreter.</p>
<p>So I think we basically have to live with possible typos to get proper
polymorphic dispatch.  If something is frequently misspelled, then you
could always put in an explicit test against <code>%_</code> for that argument:</p>
<pre>    warn &quot;Didn't you mean :the(%_«teh»)?&quot; if %_«teh»;</pre>
<p>And perhaps we could have a pragma:</p>
<pre>    use signatures :exact;</pre>
<p>But it's possible that the correct solution is to differentiate
two kinds of &quot;isa&quot;, one that derives from &quot;nextish&quot; classes,
and one that derives from &quot;superish&quot; classes.  A &quot;<code>next METHOD</code>&quot;
traversal would assume that any delegation to a super class would
be handled explicitly by the current class's methods.  That is, a
&quot;superish&quot; inheritance hides the base class from <code>.*</code> and <code>.+</code>, as well
as &quot;<code>next METHOD</code>&quot;.</p>
<p>On the other hand, if we marked the super class itself, we could
refrain from generating <code>*%</code> parameters for its methods.  Any &quot;next&quot;
dispatcher would then have to &quot;look ahead&quot; to see if the next class
was a &quot;superish&quot; class, and bypass it.  I haven't a clue what the
syntax should be though.  We could mark the class with a &quot;superish&quot;
trait, which wouldn't be inheritable.  Or we could mark it with a
Superish role, which would be inheritable, and a base class would
have to override it to impose a Nextish role instead. (But then what
if one parent class is Superish and one is Nextish?)  Or we could
even have two different metaclasses, if we decide the two kinds of
classes are fundamentally different beasts.  In that case we'd declare
them differently using &quot;class&quot; and some other keyword.  Of course,
people will want to use &quot;class&quot; for the type they prefer, and the
other keyword for the type they don't prefer.  :-)</p>
<p>But since we're attempting to bias things in favor of nextish
semantics, that would be a &quot;class&quot;, and the superish semantics might
be a &quot;guthlophikralique&quot; or some such.  <code>:-)</code></p>
<p>Seriously, if we mark the class, &quot;<code>is hidden</code>&quot; can hide the current
class from &quot;<code>next METHOD</code>&quot; semantics.  The problem with that is, how
do you apply the trait to a class in a different language?  That argues
for marking the &quot;isa&quot; instead.  So as usual when we can't make up our
minds, we'll just have it both ways.  To mark the class itself, use
&quot;<code>is hidden</code>&quot;.  To mark the &quot;isa&quot;, use &quot;<code>hides Base</code>&quot; instead of
&quot;<code>is Base</code>&quot;.  In neither case will &quot;<code>next METHOD</code>&quot; traverse to
such a class.  (And no <code>*%_</code> will be autogenerated.)</p>
<p>For example, here are two base classes that know about &quot;<code>next METHOD</code>&quot;:</p>
<pre>    class Nextish1 { method dostuff() {...; next;}
    class Nextish2 { method dostuff() {...; next;}

    class MyClass is Nextish1 is Nextish2 {
	method dostuff () {...; next;}
    }</pre>
<p>Since all the base classes are &quot;next-aware&quot;, <code>MyClass</code> knows it can
just defer to &quot;next&quot; and both parent classes' <code>dostuff</code> methods will
be called.  However, suppose one of our base classes is old-fashioned
and thinks it should call things with <code>SUPER::</code> instead.  (Or it's a
class off in Python or Ruby.)  Then we have to write our classes
more like this:</p>
<pre>    class Superish { method dostuff(...; .*SUPER::dostuff(); }
    class Nextish { method dostuff() {...; next;}

    class MyClass hides Superish is Nextish {
	method dostuff () {
	    .Superish::dostuff();	# do Superish::dostuff()
	    next;			# do Nextish::dostuff()
	}
    }</pre>
<p>Here, <code>MyClass</code> knows that it has two very different base classes.
<code>Nextish</code> knows about &quot;<code>next</code>&quot;, and <code>Superish</code> doesn't.  So it
delegates to <code>Superish::dostuff()</code> differently than it delegates to
<code>Nextish::dostuff()</code>.  The fact that it declared &quot;<code>hides Superish</code>&quot;
prevents <code>next</code> from visiting the Superish class.</p>
<a name='Collections of Classes'></a><h1>Collections of Classes</h1>
<a name='In Classes'></a><h2>In Classes</h2>
<p>We'd like to be able to support virtual inner classes.  You can't
have virtual inner classes unless you have a way to dispatch to the
actual class of the invocant.  That says to me that the solution is
bound up intimately with the method dispatcher, and the syntax of
naming an inner class has to know about the invocant in whose context
we have to start searching for the inner class.  So we could have an
explicit syntax like:</p>
<pre>    class Base {
	our class Inner { ... }
	has Inner $inner;
	submethod BUILD { .makeinner; }
	method makeinner ($self:){
	    my Inner $thing .= $self.Inner.new();
	    return $thing;
	}
    }

    class Middle is Base {
	our class Inner is Base::Inner { ... }
    }

    class Derived is Middle {
    }</pre>
<p>When you say <code>Derived.new()</code>, it creates a <code>Derived</code> object, calls
<code>Derived::BUILDALL</code>, which eventually calls <code>Base::BUILD</code>, which
makes a <code>Middle::Inner</code> object (because that's what the virtual
method <code>$self.Inner</code> returns) and puts it in a variable that of
the <code>Base::Inner</code> type (which is fine, since <code>Middle::Inner</code>
ISA <code>Base::Inner</code>.  Whew!</p>
<p>The only extra magic here is that an inner class would have to
autogenerate an accessor method (of the same name) that returns
the class.  A class could then choose to access an inner class name
directly, in which case it would get its own inner class of that
name, much like <code>$.foo</code> always gets you your own attribute.  But if
you called the inner class name as a method, it would automatically
virtualize the name, and you'd get the most derived existing version
of the class.</p>
<p>This would give us most of what RFC 254 is asking for, at the expense
of one more autogenerated method.  Use of such inner classes would
take the connivance of a base class that doesn't mind if derived
classes redefine its inner class.  Unfortunately, it would have to
express that approval by calling <code>$self.Inner</code> explicitly.  So this
solution does not go as far as letting you change classes that didn't
expect to be changed.</p>
<p>It would be possible to take it further, and I think we should.
If we say that whenever you use any global class, it makes an inner
class on your behalf that is merely an alias to the global class,
creating the accessor method as if it were an inner class, then it's
possible to virtualize the name of <i>any</i> class, as long as you're
in a context that has an appropriate invocant.  Then we'd make any
class name lookup assume <code>$self.</code> on the front, basically.</p>
<p>This may seem like a wild idea, but interestingly, we're already
proposing to do a similar aliasing in order to have multiple versions
of a module running simultaneously.  In the case of classes, it
seems perfectly natural that a new version might derive from an older
version rather than redefining everything.</p>
<p>The one fly in the ointment that I can see is that we might not
always have an appropriate invocant--for instance, outside any
method body, when we're declaring attributes. I guess when there's
no dynamic context indicating what an &quot;inner&quot; classname should mean,
it should default to the ordinary meaning in the current lexical
and/or package context.  Within a class definition, for instance,
the invocant is the metaclass, which is unhelpful.  So generally that
means that a declared attribute type will turn out to be a superclass
of the actual attribute type at run time.  But that's fine, ain't it?
You can always store a <code>Beagle</code> in a <code>Dog</code> attribute.</p>
<p>So in essence, it boils down to this.  Within a method, the invocant
is allowed to have opinions about the meanings of any class names, and
when there are multiple possible meanings, pick the most appropriate
one, where that amounts to the name you'd find if the class name were
a virtual method name.</p>
<p>Here's the example from RFC 254, translated to Perl 6 (with <code>Frog</code> made
into an explicit inner class for clarity (though it should work with
any class by the aliasing rule above)):</p>
<pre>    class Forest {
	our class Frog {
	    method speak () { say &quot;ribbit ribbit&quot;; }
	    method jump  () {...}
	    method croak () {...} # ;-)
	}

	has Frog $.frog;

	method new ($class) {
	    my Frog $frog .= new;	# MAGIC
	    return $class.bless( frog =&gt; $frog );
	}

	sub make_noise {
	    .frog.speak;	# prints &quot;ribbit ribbit&quot;
	}
    }</pre>
<p>Now we derive from <code>Forest</code>, producing <code>Forest::Japanese</code>, with its own
kind of frogs:</p>
<pre>    class Forest::Japanese is Forest {
	our class Frog is Forest::Frog {
	    method speak () { say &quot;kerokero&quot;; }
	}
    }</pre>
<p>And finally, we make a forest of that type, and tell it to make a noise:</p>
<pre>    $forest = new Forest::Japanese;
    $forest.make_noise();		# prints &quot;kerokero&quot;</pre>
<p>In the Perl 5 equivalent, that would have printed &quot;ribbit ribbit&quot; instead.
How did it do the right thing in Perl 6?</p>
<p>The difference is on the line marked &quot;<code>MAGIC</code>&quot;.  Because <code>Frog</code> was
mentioned in a method, and the invocant was of type <code>Forest::Japanese</code>
rather than of type <code>Forest</code>, the word &quot;<code>Frog</code>&quot; figured out that
it was supposed to mean a <code>Forest::Japanese::Frog</code> rather than a
<code>Forest::Frog</code>.  The name was &quot;virtual&quot;.  So we ended up creating
a forest with a frog of the appropriate type, even though it might
not have occurred to the writer of <code>Forest</code> that a subclass would
override the meaning of <code>Frog</code>.</p>
<p>So one object can think that its <code>Frog</code> is Japanese, while another
thinks it's Russian, or Mexican, or even Antarctican (if you can
find any forests there).  Base methods that talk about <code>Frog</code> will
automatically find the <code>Frog</code> appropriate to the current invocant.
This works even if <code>Frog</code> is an outer class rather than an inner class,
because any outer class referenced by a base class is automatically
aliased into the class as a fake inner class.  And the derived class
doesn't have to redefine its <code>Frog</code> by declaring an inner class either.
It can just alias (or use) a different outer <code>Frog</code> class in as its
fake inner class.  Or even a different version of the same <code>Frog</code> class,
if there are multiple versions of it in the library.</p>
<p>And it just works.</p>
<a name='In Modules'></a><h2>In Modules</h2>
<p>It's also possible to put a collection of classes into a module,
but that doesn't buy you much except the ability to pull them all
in with one <code>use</code>, and manage them all with one version number.
Which has a lot to be said for it--in the next section.</p>
<a name='Versioning'></a><h1>Versioning</h1>
<p>Way back at the beginning, we claimed that a file-scoped class
declaration:</p>
<pre>    class Dog;
    ...</pre>
<p>is equivalent to the corresponding block-scoped declaration:</p>
<pre>    class Dog {...}</pre>
<p>While that's true, it isn't the whole truth.  A file-scoped class
(or module, or package) is the carrier of more metadata than
a block-scoped declaration.  Perl 6 supports a notion of versions
that is file based.  But even a class name plus a version is not
sufficient to name a module--there also has to be a naming authority,
which could be a URI or a CPAN id.  This will be discussed more
fully in Apocalypse 11, but for now we can make some predictions.</p>
<p>The extra metadata has to be associated with the file somehow.  It
may be implicit in the filename, or in the directory path leading
to the file.  If so, then Perl 6 has to collect up this information
as modules are loaded and associate it with the top level class or
module as a set of properties.</p>
<p>It's also possible that a module could declare properties explicitly
to define these and other bits of metadata:</p>
<pre>    author        <a href='http://www.some.com/~jrandom' target='_blank'>www.some.com</a>
    version       1.2.1
    creator       Joe Random
    description   This class implements camera obscura.
    subject       optics, boxes
    language      ja_JP
    licensed      Artistic|GPL</pre>
<p>Modules posted to CPAN or entered into any standard Perl 6 library are
required to declare some set of these properties so that installations
can know where to keep them, such that multiple versions by different
authors can coexist, all of them available to any installed version
of Perl.  (This is a requirement for any Perl 6 installation.  We're
tired of having to reinstall half of CPAN every time we patch Perl.
We also want to be able to run different versions of the <code>Frog</code> module
simultaneously when the <code>Frog</code> requirements of the modules we use are
contradictory.)</p>
<p>It's possible that the metadata is supplied by both the declarations
and by the file's name or location in the library, but if so, it's
a fatal error to use a module for which those two sources contradict
each other as to author or version.  (In theory, it could also be a
fatal error to use modules with incompatible licensing, but a kind
warning might be more appreciated.)  Likely there will also be some
kind of automatic checksumming going on as well to prevent fraudulent
distributions of code.</p>
<p>It might simplify things if we make an <code>identifier</code> metadatum that
incorporates all of naming authority, package name, and version.
But the individual parts still have to be accessible, if only as
components of <code>identifier</code>.  However we structure it, we should make
the <code>identifier</code> the actual declared full name of the class, yet another
one of those &quot;long names&quot; that include extra parameters.</p>
<a name='Version Declarations'></a><h2>Version Declarations</h2>
<p>The syntax of a versioned class declaration looks like this:</p>
<pre>    class Dog-1.2.1-cpan:JRANDOM;
    class Dog-1.2.1-<a href='http://www.some.com/~jrandom;' target='_blank'>www.some.com</a>
    class Dog-1.2.1-mailto:jrandom@some.com;</pre>
<p>Perhaps those could also have short forms, presuming we can distinguish
CPAN ids, web pages, and email addresses by their internal forms.</p>
<pre>    class Dog-1.2.1-JRANDOM;
    class Dog-1.2.1-www.some.com/~jrandom;
    class <a href='mailto:Dog-1.2.1-jrandom@some.com'>Dog-1.2.1-jrandom@some.com</a>;</pre>
<p>Or maybe using email addresses is a bad idea now in the modern
Spam Age.  Or maybe Spam Ages should be plural, like the Dark Ages...</p>
<p>In any event, such a declaration automatically aliases the full name
of the class (or module) to the short name.  So for the rest of the
scope, <code>Dog</code> refers to the longer name.</p>
<p>(Though if you refer to <code>Dog</code> within a method, it's considered a
virtual class name, so Perl will search any derived classes for a
redefined inner <code>Dog</code> class (or alias) before it settles on the
least-derived aliased <code>Dog</code> class.)</p>
<p>We lied slightly when we said earlier that only the file-scoped class
carries extra metadata.  In fact, all of the classes (or modules, or
packages) defined within your file carry metadata, but it so happens
that the version and author of all your extra classes (or modules, or
packages) are forced to be the same as the file's version and author.
This happens automatically, and you may not override the generation of
these long names, because if you did, different file versions could
and would have version collisions of their interior components, and
that would be catastrophic.  In general you can ignore this, however,
since the long names of your extra classes are always automatically
aliased back down to the short names you thought you gave them in the
first place.  The extra bookkeeping is in there only so that Perl can
keep your classes straight when multiple versions are running at the
same time.  Just don't be surprised when you ask for the name of
the class and it tells you more than you expected.</p>
<a name='Use of Version and Author Wildcards'></a><h2>Use of Version and Author Wildcards</h2>
<p>Since these long names are the actual names of the classes, when you say:</p>
<pre>    use Dog;</pre>
<p>you're really asking for something like:</p>
<pre>    use Dog-(Any)-(Any);</pre>
<p>And when you say:</p>
<pre>    use Dog-1.2.1;</pre>
<p>you're really asking for:</p>
<pre>    use Dog-1.2.1-(Any);</pre>
<p>Note that the <code>1.2.1</code> specifies an <i>exact</i> match on the version
number.  You might think that it should specify a minimum version.
However, people who want stable software will specify an exact version
and stick with it.  They don't want <code>1.2.1</code> to mean a minimum version.
They know <code>1.2.1</code> works, so they want that version nailed down
forever--at least for now.</p>
<p>To match more than one version, put a range operator in parens:</p>
<pre>    use Dog-(1.2.1..1.2.3);
    use Dog-(1.2.1..^1.3);
    use Dog-(1.2.1...);</pre>
<p>[Update: An infinite range is now written <code>(1.2.1..*)</code>.</p>
<p>What goes inside the parens is in fact any valid smartmatch selector:</p>
<pre>    use Dog-(1.2.1 | 1.3.4)-(/:i jrandom/);
    use Dog-(Any)-(/^cpan\:/)</pre>
<p>And in fact they could be closures too.  These means the same thing:</p>
<pre>    use Dog-{$^ver ~~ 1.2.1 | 1.3.4}-{$^auth ~~ /:i jrandom/};
    use Dog-{$^ver ~~ Any}-{$^auth ~~ /^cpan\:/}</pre>
<p>In any event, however you select the module, its full name is
automatically aliased to the short name for the rest of your lexical
scope.  So you can just say</p>
<pre>    my Dog $spot .= new(&quot;woof&quot;);</pre>
<p>and it knows (even if you don't) that you mean</p>
<pre>    my Dog-1.3.4-cpan:JRANDOM $spot .= new(&quot;woof&quot;);</pre>
<p>(Again, if you refer to <code>Dog</code> within a method, it's a virtual class
name, so Perl will search any derived classes for a redefined <code>Dog</code> class
before it settles on the outermost aliased <code>Dog</code> class.)</p>
<p>[Update: You can also prefix the module name with the language to
borrow it from, like &quot;<code>use perl5:DBI;</code>&quot;.]</p>
<a name='Introspection'></a><h1>Introspection</h1>
<p>It's easy to specify what Perl 6 will provide for introspection:
the union of what Perl 6 needs and whatever Parrot provides for
other languages.  <code>;-)</code></p>
<p>In the particular case of class metadata, the interface should
generally be via the class's metaclass instance--the object of type
<code>MetaClass</code> that was in charge of building the class in the first
place.  The metamethods are in the metaobject, not in the class object.
(Well, actually, those are the same object, but a class object ignores
the fact that it's also a metaobject, and dispatches by default to its
own methods, not the ones defined by the metaclass.)</p>
<p>[Update: It's not true that the class object is the same as the metaobject.]</p>
<p>To get to the metamethods of an ordinary class object you have to use
the <code>.meta</code> method:</p>
<pre>    MyClass.getmethods()	# call MyClass's .getmethods method
    MyClass.meta.getmethods()	# get the method list of MyClass</pre>
<p>Unless <code>MyClass</code> has defined or inherited a <code>.getmethods</code> method, the
first call is an error.  The second is guaranteed to work for Perl 6's
standard <code>MetaClass</code> objects.  You can also call <code>.meta</code> on any ordinary
object:</p>
<pre>    $obj.meta.getmethods();</pre>
<p>That's equivalent to</p>
<pre>    $obj.dispatcher.meta.getmethods();</pre>
<p>[Update: There's no <code>.dispatcher</code> since all objects have a <code>.meta</code> now, and
all objects of a class including class objects are of the same type.]</p>
<p>As for which parts of a class are considered metadata--they all are,
if you scratch hard enough.  Everything that is not stored directly as
a trait or property really ought to have some kind of trait-like method
to access it.  Even the method body closures have to be accessible
as traits, since the <code>.wrap</code> method needs to have something to put
its wrapper around.</p>
<p>Minimally, we'll have user-specified class traits that look like this:</p>
<pre>    identifier    Dog-1.2.1-<a href='http://www.some.com/~jrandom' target='_blank'>www.some.com</a>
	name      Dog
	version   1.2.1
	authority <a href='http://www.some.com/~jrandom' target='_blank'>www.some.com</a>
    author        Joe Random
    description   This class implements camera obscura.
    subject       optics, boxes
    language      ja_JP
    licensed      Artistic|GPL</pre>
<p>And there may be internal traits like these:</p>
<pre>    isa           list of parent classes
    roles         list of roles
    disambig      how to deal with ambiguous method names from roles
    layout        P6opaque, P6hash, P5hash, P5array, PyDict, Cstruct, etc.</pre>
<p>The <code>layout</code> determines whether one class can actually derive
from another or has to fake it.  Any P6opaque class can compatibly
inherit from any other P6opaque class, but if it inherits from any
P5 class, it must use some form of delegation to another invocant.
(Hopefully with a smart enough invocant reference that, if the
delegated object unknowingly calls back into our layout system,
we can recover the original object reference and maintain some kind
of compositional integrity.)</p>
<p>The metaclass's <code>.getmethods</code> method returns method-descriptor objects
with at least the following properties:</p>
<pre>    name		the name of the method
    signature		the parameters of the method
    returns		the return type of the method
    multi		whether duplicate names are allowed
    do			the method body</pre>
<p>The <code>.getmethods</code> method has a selector parameter that lets you
specify whether you want to see a flattened or hierarchical view,
whether you're interested in private methods, and so forth.  If you
want a hierarchical view, you only get the methods actually defined
in the class proper.  To get at the others, you follow the &quot;isa&quot;
trait to find your parent classes' methods, and you follow the &quot;roles&quot;
trait to get to role methods, and from parents or roles you may also
find links to further parents or roles.</p>
<p>The <code>.getattributes</code> method returns a list of attribute descriptors
that have traits like these:</p>
<pre>    name
    type
    scope
    rw
    private
    accessor
    build</pre>
<p>Additionally they can have any other variable traits that can reasonably be
applied to object attributes, such as <code>constant</code>.</p>
<p>Strictly speaking, metamethods like <code>.isa()</code>, <code>.does()</code>, and <code>.can()</code>
should be called through the meta object:</p>
<pre>    $obj.meta.can(&quot;bark&quot;)
    $obj.meta.does(Dog)
    $obj.meta.isa(Mammal)</pre>
<p>And they can always be called that way.  For convenience you can often
omit the <code>.meta</code> call because the base <code>Object</code> type translates
any unrecognized <code>.foo()</code> into <code>.meta.foo()</code> if the meta class
has a method of that name.  But if a derived class overrides such a
metamethod, you have to go through the <code>.meta</code> call explicitly to
get the original call.</p>
<p>In previous Apocalypses we said that:</p>
<pre>    $obj ~~ Dog</pre>
<p>calls:</p>
<pre>    $obj.isa(Dog)</pre>
<p>That is not longer the case--you're actually calling:</p>
<pre>    $obj.meta.does(Dog)</pre>
<p>which is true if <code>$obj</code> either &quot;does&quot; or &quot;isa&quot; <code>Dog</code> (or &quot;isa&quot;
something that &quot;does&quot; <code>Dog</code>).  That is, it asks if <code>$obj</code> is likely
to satisfy the interface that comes from the <code>Dog</code> role or class.
The <code>.isa</code> method, by contrast, is strictly asking if <code>$obj</code> inherits
from the <code>Dog</code> class.  It's erroneous to call it on a role.  Well,
okay, it's not strictly erroneous.  It will just never return true.
The optimizer will love you, and remove half your code.</p>
<p>Note that either of <code>.does</code> or <code>.isa</code> can lie, insofar as you might
include an interface that you later override parts of.  When in doubt,
rely on <code>.can</code> instead.  Better yet, rely on your dispatcher to
pick the right method without trying to second guess it.  (And then
be prepared to catch the exception if the dispatcher throws up its
hands in disgust...)</p>
<p>By the way, unlike in Perl 5 where <code>.can</code> returns a single routine
reference, Perl 6's version of <code>.meta.can</code> returns a &quot;WALK&quot; iterator
for a set of routines that match the name.  When dereferenced, the
iterator gets fed to a dispatcher as if the method had been called
in the first place.  Note that any wildcard methods (via delegation
or <code>AUTOLOAD</code>) are included by default in this list of potential
handlers, so there is no reason for subclasses to have to redefine
<code>.can</code> to reflect the new names.  This does potentially weaken the
meaning of <code>.can</code> from &quot;definitely has a method of this name&quot; to
&quot;definitely has one or more methods in one or more classes that will
try to handle this.&quot;  But that's probably closer to what you want,
and the best we can do when people start fooling around with wildcard
methods under MI.</p>
<p>However, that being said, many classes may wish to dynamically
specify at the last moment which methods they can or cannot handle.
That is, they want a hook to allow a class to declare names even while
the <code>.can</code> candidate list is being built.  By default <code>.meta.can</code>
includes all wildcard delegations and autoloads at the end of the list.
However, it will exclude from the list of candidates any class that
defines its own <code>AUTOMETH</code> method, on the assumption that each
such <code>AUTOMETH</code> method has already had its chance to add any
callable names to the list.  If the class's <code>AUTOMETH</code> wishes to
supply a method, it should return a reference to that method.</p>
<p>Do not confuse <code>AUTOMETH</code> with <code>AUTOMETHDEF</code>.  The former is
equivalent to declaring a stub declaration.  The latter is equivalent
to supplying a body for an existing stub.  Whether <code>AUTOMETH</code>
actually creates a stub, or <code>AUTOMETHDEF</code> actually creates a body,
is entirely up to those routines.  If they wish to cache their results,
of course, then they should create the stub or body.</p>
<p>There are corresponding <code>AUTOSUB</code> and <code>AUTOSUBDEF</code> hooks.
And <code>AUTOVAR</code> and <code>AUTOVARDEF</code> hooks.  These all pretty much
make <code>AUTOLOAD</code> obsolete.  But <code>AUTOLOAD</code> is still there for old times's sake.</p>
<p>[Update: These are all subsumed into <code>CANDO</code> multies and <code>AUTODEF</code> submethods.]</p>
<a name='Other Non-OO Decisions'></a><h1>Other Non-OO Decisions</h1>
<p>A lot of time went by while I was in the hospital last year, so we
ended up polishing up the design of Perl 6 in a number of areas not
directly related to OO.  Since I've already got your attention
(and we're already 90% of the way through this Apocalypse), I might
as well list these decisions here.</p>
<a name='Exportation'></a><h2>Exportation</h2>
<p>The trait we'll use for exportation (typically from modules but also
from classes pretending to be modules) is <code>export</code>:</p>
<pre>                                               # Tagset...
    sub foo is export(:DEFAULT)         {...}  #  :DEFAULT, :ALL
    sub bar is export(:DEFAULT :others) {...}  #  :DEFAULT, :ALL, :others
    sub baz is export(:MANDATORY)       {...}  #  (always exported)
    sub bop is export                   {...}  #  :ALL
    sub qux is export(:others)          {...}  #  :ALL, :others</pre>
<p>Compared to Perl 5, we've basically made it easier to mark something
as exportable, but more difficult to export something by default.
You no longer have to declare your tagsets separately, since <code>:foo</code>
parameters are self-declaring, and the module will automatically
build the tagsets for you from the export trait arguments.</p>
<a name='The gather/take Construct'></a><h2>The gather/take Construct</h2>
<p>We used one example of the conjectural gather/take construct.  A gather
executes a closure, returning a list of all the values returned by
<code>take</code> within its lexical scope.  In a lazy context it might run as
a coroutine.  There probably ought to be a dynamically scoped variant.
Unless it should be dynamic by default, in which case there probably
ought to be a lexically scoped variant...</p>
<a name=':foo() Adverbs'></a><h2>:foo() Adverbs</h2>
<p>There's a new pair syntax that is more conducive to use as option
arguments.  This syntax is reminiscent of both the Unix command
line syntax and the I/O layers syntax of Perl 5.  But unlike Unix
command-line options, we use colon to introduce the option rather than
the overly negative minus sign.  And unlike Perl 5's layers options, you
can use these outside of a string.</p>
<p>We haven't discarded the old pair syntax.  It's still more readable
for certain uses, and it allows the key to be a non-identifier.
Plus we can define the new syntax in terms of it:</p>
<pre>    Old				New
    ---				---
    foo =&gt; $bar			:foo($bar)
    foo =&gt; [1,2,3,@many]	:foo[1,2,3,@many]
    foo =&gt; «alice bob charles»	:foo«alice bob charles»
    foo =&gt; 'alice'		:foo«alice»
    foo =&gt; { a =&gt; 1, b =&gt; 2 }	:foo{ a =&gt; 1, b =&gt; 2 }
    foo =&gt; { dostuff() }	:foo{ dostuff() }
    foo =&gt; 0			:foo(0)
    foo =&gt; 1			:foo</pre>
<p>It's that last one that's the real winner for passing boolean options.
One other nice thing is that if you have several options in a row you
don't have to put commas between:</p>
<pre>    $handle = open $file, :chomp :encoding«guess» :ungzip or die &quot;Oops&quot;;</pre>
<p>It might be argued that this conflicts the :foo notation for private
methods.  I don't think it's a problem because method names never
occur in isolation.</p>
<p>[Update: We ended up changing private methods to use <code>!</code> instead.  Also,
there's a <code>:!foo</code> form to mean <code>:foo(0)</code>.]</p>
<p>Oh, one other feature of option pairs is that certain operations can
use them as adverbs.  For instance, you often want to tell the range
operator how much to skip on each iteration.  That looks like this:</p>
<pre>    1..100 :by(3)</pre>
<p>Note that this only works where an operator is expected rather than a term.
So there's no confusion between:</p>
<pre>    randomlistop 1..100 :by(3)</pre>
<p>and</p>
<pre>    randomlistop 1..100, :by(3)</pre>
<p>In the latter case, the option is being passed to <code>randomlistop()</code>
rather than the <code>infix:..</code> operator.</p>
<p>[Update: That's <code>infix:&lt;..&gt;</code> now.]</p>
<a name='Special Quoting of Identifiers Inside Curlies Going Away!'></a><h2>Special Quoting of Identifiers Inside Curlies Going Away!</h2>
<p>Novice Perl 5 programmers are continually getting trapped by
subscripts that autoquote unexpectedly.  So in Perl 6, we'll remove
that special case.  %hash{shift} now always calls the shift function,
because the inside of curlies is always an expression.  Instead,
if you want to subscript a hash with a constant string, or a slice
of constant strings, use the new French qw//-ish brackets like this:</p>
<pre>    %hash«alice»		# same as %hash{'alice'}
    %hash«alice bob charlie»	# same as %hash{'alice','bob','charlie'}</pre>
<p>Note in particular that, since slices in Perl 6 are determined by
the subscript only, not the sigil, this:</p>
<pre>    %hash«alice» = @x;</pre>
<p>evaluates the right side in scalar context, while</p>
<pre>    %hash«alice bob charlie» = @x;</pre>
<p>evaluates the right side in list context.</p>
<p>[Update: That is now false.  A subscripted lvalue expression is always
assumed to be scalar unless it is in parentheses.)</p>
<p>As with all other uses of the French quotes in Perl 6, you can always use:</p>
<pre>    %hash&lt;&lt;alice&gt;&gt; = @x;</pre>
<p>if you can't figure out how to type <code>^K &lt; &lt;</code> or <code>^K &gt; &gt;</code> in vim.</p>
<p>On the other hand, if you've got a fully Unicode aware editor, you
could probably write some macros to use the big double angles from
Asian languages:</p>
<pre>    %hash《alice》 = @x;</pre>
<p>But by default we only provide the Latin-1 compatible versions.
It would be easy to overuse Unicode in Perl 6, so we're trying to
underuse Unicode for small values of 6.  (Not to be confused with ⁶,
or ⅵ.)</p>
<p>[Update: We switched to bare angles for this.  Double angles now
do shell-like interpolation, so double angles relate to single angles
much like double quotes relate to single quotes.]</p>
<a name='Vector Operators Renamed Back to &quot;hyper&quot; Operators'></a><h2>Vector Operators Renamed Back to &quot;hyper&quot; Operators</h2>
<p>The mathematicians got confused when we started talking about &quot;vector&quot;
operators, so these dimensionally dwimming versions of scalar operators
are now called hyper operators (again).  Some folks see operations like</p>
<pre>    @a »*« @b</pre>
<p>as totally useless, and maybe they are--to a mathematician.  But to
someone simply trying to calculate a bunch of things in parallel
(think cellular automata, or aerodynamic simulations, for instance), they
make a lot of sense.  And don't restrict your thinking to math
operators.  How about appending a newline to every string before
printing it out:</p>
<pre>    print @strings »~« &quot;\n&quot;;</pre>
<p>Of course,</p>
<pre>    for @strings {say}</pre>
<p>is a shorter way to do the same thing.  (&quot;<code>say</code>&quot; is just Perl 6's version
of a printline function.)</p>
<a name='Unary Hyper Operators Now Use One Quote Rather Than Two'></a><h2>Unary Hyper Operators Now Use One Quote Rather Than Two</h2>
<p>Unary operators read better if they only &quot;hyper&quot; on the side where
there's an actual argument:</p>
<pre>    @neg = -« @pos;
    @indexes = @x »++;</pre>
<p>And in particular, I consider a method spec like <code>.bletch(1,2,3)</code> to
be a unary postfix operator, and it would be really ugly to say:</p>
<pre>    @objects».bletch(1,2,3)«</pre>
<p>So that's just:</p>
<pre>    @objects».bletch(1,2,3)</pre>
<p>In general, binary operators still take &quot;hypers&quot; on both sides, indicating
that both sides participate in the dwimmery.</p>
<pre>    @a »+« @a</pre>
<p>To indicate that one side or the other should be evaluated as a scalar
before participating in the hyperoperator, you can always put in a
context specifier:</p>
<pre>    @a »+« +@a</pre>
<a name='$thumb.twiddle No Longer Requires Parens When Interpolated'></a><h2><code>$thumb.twiddle</code> No Longer Requires Parens When Interpolated</h2>
<p>In Apocalypse 2 we said that any method interpolated into a double-quoted
string has to have parentheses.  We're throwing out that special rule
in the interests of consistency.  Now if you want to interpolate a
variable followed by an &quot;accidental&quot; dot, use one of these:</p>
<pre>    $($var).twiddle
    $var\.twiddle</pre>
<p>Yes, that will make it a little harder to translate Perl 5 to Perl 6.</p>
<p>(Parentheses are still required if there are any arguments, however.)</p>
<p>[Update: We're back to requiring parens on methods.  In fact, we've gone
the other way--we now require square brackets on arrays and curlies on
hashes.  And a bare closure also interpolates.  The <i>only</i> interpolator
that doesn't require some kind of bracketing terminator is a simple
scalar.  See S2.]</p>
<a name='The =:= Identity Operator'></a><h2>The =:= Identity Operator</h2>
<p>There is a new <code>=:=</code> identity operator, which tests to see if
two objects are the same object.  The association with the <code>:=</code>
binding operator should be obvious.  (Some classes such as integers
may consider all objects of the same value to be a single object,
in a Platonic sense.)</p>
<p>Hmm?  No, there is no associated assignment operator.  And if there were,
I wouldn't tell you about it.  Sheesh, some people...</p>
<p>But there is, of course, a hyper version:</p>
<pre>    @a »=:=« @b</pre>
<a name='New Grammatical Categories'></a><h2>New Grammatical Categories</h2>
<p>The current set of grammatical categories for operator names is:</p>
<pre>    Category				Example of use
    --------				--------------
    coerce:as				123 as BigInt, BigInt(123)
    self:sort				@array.=sort
    term:...				$x = {...}
    prefix:+				+$x
    infix:+				$x + $y
    postfix:++				$x++
    circumfix:[]			[ @x ]
    postcircumfix:[]			$x[$y] or $x .[$y]
    rule_modifier:p5			m:p5//
    trait_verb:handles			has $.tail handles «wag»
    trait_auxiliary:shall		my $x shall conform«TR123»
    scope_declarator:has		has $.x;
    statement_control:if		if $condition {...} else {...}
    infix_postfix_meta_operator:=	$x += 2;
    postfix_prefix_meta_operator:»	@array »++
    prefix_postfix_meta_operator:«	-« @magnitudes
    infix_circumfix_meta_operator:»«	@a »+« @b</pre>
<p>Now, you may be thinking that some of these have long, unwieldy names.
You'd be right.  The longer the name, the longer you should think
before adding a new operator of that category.  (And the length of
time you should think probably scales exponentially with the length of
the name.)</p>
<p>[Update: The actual operator name must be quoted like a hash subscript:</p>
<pre>    coerce:&lt;as&gt;					123 as BigInt, BigInt(123)
    self:&lt;sort&gt;					@array.=sort
    term:&lt;...&gt;					$x = {...}
    prefix:&lt;+&gt;					+$x
    infix:&lt;+&gt;					$x + $y
    postfix:&lt;++&gt;				$x++
    circumfix:&lt;[ ]&gt;				[ @x ]
    postcircumfix:&lt;[ ]&gt;				$x[$y] or $x .[$y]
    rule_modifier:&lt;p5&gt;				m:p5//
    trait_verb:&lt;handles&gt;			has $.tail handles &lt;wag&gt;
    trait_auxiliary:&lt;shall&gt;			my $x shall conform&lt;TR123&gt;
    scope_declarator:&lt;has&gt;			has $.x;
    statement_control:&lt;if&gt;			if $condition {...} else {...}
    statement_modifier:&lt;if&gt;			... if $condition
    infix_postfix_meta_operator:&lt;=&gt;		$x += 2;
    postfix_prefix_meta_operator:{'»'}		@array »++
    prefix_postfix_meta_operator:{'«'}		-« @magnitudes
    infix_circumfix_meta_operator:{'»','«'}	@a »+« @b</pre>
<p>Please note that the &quot;hole&quot; in circumfixes is now specified by
slice notation.  There is no longer any special split-down-the-middle
rule.]</p>
<a name='Assignment to state variable declaration now does &quot;first&quot; semantics.'></a><h2>Assignment to <code>state</code> variable declaration now does &quot;first&quot; semantics.</h2>
<p>As we talked about earlier, assignment to a &quot;<code>has</code>&quot; variable is really
pseudo-assignment representing a call to the &quot;<code>build</code>&quot; trait.  In the
same way, assignment to <code>state</code> variables (Perl's version of lexically
scoped &quot;static&quot; variables), is taken as pseudo-assignment representing
a call to the &quot;<code>first</code>&quot; trait.  The first time through a piece of code
is when state variables typically like to be initialized.  So saying:</p>
<pre>    state $pc = $startpc;</pre>
<p>is equivalent to</p>
<pre>    state $pc is first( $startpc );</pre>
<p>which means that it will pay attention to the <code>$startpc</code> variable
only the first time this block is ever executed.  Note that any side
effects within the expression will only happen the first time through.
If you say</p>
<pre>    state $x = $y++;</pre>
<p>then that statement will only ever increment <code>$y</code> once.  If that's
not what you want, then use a real assignment as a separate statement:</p>
<pre>    state $x;
    $x = $y++;</pre>
<p>The <code>:=</code> and <code>.=</code> operators also attempt to do what you mean, which
in the case of:</p>
<pre>    state $x := $y++;</pre>
<p>still probably doesn't do what you want.  <code>:-)</code></p>
<p>In general, any &quot;preset&quot; trait is smart about when to apply its value
to the container it's being applied to, such that the value is set
statically if that's possible, and if that's not possible, it is set
dynamically at the &quot;correct&quot; moment.</p>
<p>For ordinary assignment to a &quot;<code>my</code>&quot; variable, that correct moment just
happens to be every time it is executed, so <code>=</code> represents ordinary
assignment.  If you want to force an initial value at execution time
that was calculated earlier, however, then just use ordinary assignment
to assign the results of a precalculated block:</p>
<pre>    my @canines = INIT { split slurp &quot;%ENV«HOME»/.canines&quot; };</pre>
<p>It's only the <code>has</code> and <code>state</code> declarators that redefine assignment
to set defaults with traits.  (For <code>has</code>, that's because the
actual attribute variable won't exist until the object is created.
For <code>state</code>, that's because we want the default to be &quot;first time
through&quot;.)  But you can use any of the traits on any variable for
which it makes sense.  For instance, just because we invented the
&quot;<code>first</code>&quot; initializer for state variables:</p>
<pre>    state $lexstate is first(0);</pre>
<p>doesn't mean you can't use it to initialize any variable only the
first time through a block of code:</p>
<pre>    my $foo is first(0);</pre>
<p>However, it probably doesn't make a lot of sense on a &quot;<code>my</code>&quot; variable,
unless you really want it to be undefined the second time through.
It does make a little more sense on an &quot;<code>our</code>&quot; variable that will hang
onto its value like a state variable:</p>
<pre>    our $counter is first(0);</pre>
<p>An assignment would often be wrong in this case.  But generally,
the naive user can simply use assignment, and it will usually do what
they want (if occasionally more often than they want).  But it does
exactly what they want on <code>has</code> and <code>state</code> variables--presuming
they are savvy enough to want what it actually does... <code>:-)</code></p>
<p>So as with <code>has</code> variables, <code>state</code> variables can be initialized with
precomputed values:</p>
<pre>    state $x = BEGIN { calc() }
    state $x = CHECK { calc() }
    state $x = INIT  { calc() }
    state $x = FIRST { calc() }
    state $x = ENTER { calc() }</pre>
<p>which mean something like:</p>
<pre>    state $x is first( BEGIN { calc() } )
    state $x is first( CHECK { calc() } )
    state $x is first( INIT  { calc() } )
    state $x is first( FIRST { calc() } )
    state $x is first( ENTER { calc() } )</pre>
<p>Note, however, that the last one doesn't in fact make much sense,
since <code>ENTER</code> happens more frequently than <code>FIRST</code>.  Come to think of it,
doing <code>FIRST</code> inside a <code>first</code> doesn't buy you much either...</p>
<a name='The length() function is gone'></a><h2>The length() function is gone</h2>
<p>In Perl 6 you're not going to see</p>
<pre>    my $sizeofstring = length($string);</pre>
<p>That's because &quot;length&quot; has been deemed to be an insufficiently
specified concept, because it doesn't specify the units. Instead,
if you want the length of something in characters you use</p>
<pre>    my $sizeinchars = chars($string);</pre>
<p>and if you want the size in elements, you use</p>
<pre>    my $sizeinelems = elems(@array);</pre>
<p>This is more orthogonal in some ways, insofar as you can now ask for
the size in chars of an array, and it will add up all the lengths of
the strings in it for you:</p>
<pre>    my $sizeinchars = chars(@array);</pre>
<p>And if you ask for the number of elems of a scalar, it knows to
dereference it:</p>
<pre>    my $ref = [1,2,3];
    my $sizeinelems = elems($ref);</pre>
<p>These are, in fact, just generic object methods:</p>
<pre>    @array.elems
    $string.chars
    @array.chars
    $ref.elems</pre>
<p>And the functional forms are just multimethod calls.  (Unless they're
indirect object calls...who knows?)</p>
<p>You can also use <code>%hash.elems</code>, which returns the number of pairs in
the hash. I don't think <code>%hash.chars</code> is terribly useful, but it will
tell you how many characters total there are in the values.  (The key
lengths are ignored, just like the integer &quot;keys&quot; of an ordinary array.)</p>
<p>Actually, the meaning of <code>.chars</code> varies depending on your current
level of Unicode support. To be more specific, there's also:</p>
<pre>    $string.bytes
    $string.codepoints
    $string.graphemes
    $string.letters</pre>
<p>[Update: Those are shortened to <code>.codes</code>, <code>.graphs</code>, and <code>.langs</code> now.]</p>
<p>...none of which should be confused with:</p>
<pre>    $string.columns</pre>
<p>or its evil twin:</p>
<pre>    $string.pixels</pre>
<p>Those last two require knowledge of the current font and rendering
engine, in fact.  Though <code>.columns</code> is likely to be pretty much the
same for most Unicode fonts that restrict themselves to single and
double-wide characters.</p>
<a name='String positions'></a><h2>String positions</h2>
<p>A corollary to the preceding is that string positions are not numbers.
If you say either</p>
<pre>    $pos = index($string, &quot;foo&quot;);</pre>
<p>or</p>
<pre>    $string ~~ /foo/; $pos = $string.pos;</pre>
<p>then <code>$pos</code> points to that location in that string.  If you ask for
the numeric value of <code>$pos</code>, you'll get a number, but which number you
get can vary depending on whether you're currently treating characters
as bytes, codepoints, graphemes, or letters.  When you pass a <code>$pos</code>
to <code>substr($string, $pos, 3)</code>, you'll get back &quot;<code>foo</code>&quot;, but not
because it counted over some number of characters.  If you use <code>$pos</code>
on some other string, then it has to interpret the value numerically
in the current view of what &quot;character&quot; means.  In a boolean context,
a position is true if the position is defined, even if that position
would evaluate to 0 numerically.  (<code>index</code> and <code>rindex</code> return undef
when they &quot;run out&quot;.)</p>
<p>And, in fact, when you say <code>$len = .chars</code>, you're really getting
back the position of the end of the string, which just happens to
numerify to the number of characters in the string in the current view.
A consequence of the preceding rules is that <code>&quot;&quot;.chars</code> is true,
but <code>+&quot;&quot;.chars</code> is false.  So Perl 5 code that says <code>length($string)</code>
needs to be translated to <code>+chars($string)</code> if used in a boolean
context.</p>
<p>Routines like <code>substr</code> and <code>index</code> take either positions or integers
for arguments.  Integers will automatically be turned into positions
in the current view.  This may involve traversing the string for
variable-width representations, especially when working with combining
characters as parts of graphemes.  Once you're working with abstract
positions, however, they are efficient.  So</p>
<pre>    while $pos = index($string, &quot;fido&quot;, $pos + 1) {...}</pre>
<p>never has to rescan the string.</p>
<p>The other point of all this is that you can pass <code>$pos</code> or <code>$len</code> to
another module, and <i>it doesn't matter</i> if you're doing offsets in
graphemes and they are doing offsets in codepoints.  They get the
correct position by their lights, even though the number of characters
looks different.  The main constraint on this is that if you pass
a position from a lower Unicode support level to a higher Unicode
support level, you can end up with a position that is inside what
you think of as a unitary character, whether that's a byte within a
codepoint, or a codepoint within a grapheme or letter. If you deref
such a position, an exception is thrown.  But generally high-level
routines call into low-level routines, so the issue shouldn't arise
all that often in practice.  However, low-level routines that want
to be called from high-level routines should strive not to return
positions inside high-level characters--the fly in the ointment being
that the low-level routine doesn't necessarily know the Unicode level
expected by the calling routine.  But we have a solution for that...</p>
<p>High-level routines that suspect they may have a &quot;partial position&quot; can
call <code>$pos.snap</code> (or <code>$pos.=snap</code>) to round up to the next integral
position in the current view, or (much less commonly) <code>$pos.snapback</code>
(or <code>$pos.=snapback</code>) to round down to the next integral position
in the current view.  This only biases the position rightward or
leftward.  It doesn't actually do any repositioning unless we're about
to throw an exception.  So this allows the low-level routine to return
<code>$pos.snap</code> without knowing at the time how far forward to snap.
The actual snapping is done later when the high-level routine tries
to use the position, and at that point we know which semantics to
snap forward under.</p>
<p>By the way, if you bind to a position rather than assign, it tracks
the string in question:</p>
<pre>    my $string = &quot;xyz&quot;;
    my $endpos := $string.chars;	# $endpos == 3
    substr($string,0,0,&quot;abc&quot;);		# $endpos == 6, $string = &quot;abcxyz&quot;</pre>
<p>Deletions of string around a position cause the position to be reduced
to the beginning of the deletion.  Insertions at a position are assumed
to be after that position.  That is, the position stays pointing to
the beginning of the newly inserted string, like this:</p>
<pre>    my $string = &quot;xyz&quot;;
    my $endpos := $string.chars;	# $endpos == 3
    substr($string,2,1,&quot;abc&quot;);		# $endpos == 2, $string = &quot;xyabc&quot;</pre>
<p>Hence concatenation never updates any positions.  Which means that
sometimes you just have to call <code>.chars</code> again...  (Perhaps we'll
provide a way to optionally insert before any matching position.)</p>
<p>Note that positions try very hard not to get demoted to integers.
In particular, position objects overload addition and substraction
such that</p>
<pre>    $string.chars - 1
    index($string, &quot;foo&quot;) + 2</pre>
<p>are still position objects with an implicit reference into the string.
(Subtracting one position object from another results in an integer,
however.)</p>
<a name='The New &quot;&amp;&quot; Separator in Regexen'></a><h2>The New &quot;&amp;&quot; Separator in Regexen</h2>
<p>Analogous to the disjunctional <code>|</code> separator, we're also putting in a
conjunctional <code>&amp;</code> separator into our regex syntax:</p>
<pre>    &quot;DOG&quot; ~~ /D [ &lt;vowel&gt;+ &amp; &lt;upper&gt;+ ] G/</pre>
<p>The semantics of it are pretty straightforward, as long as you
realize that all of the ANDed assertions have to match <i>with the
same length</i>.  More precisely, they have to start and stop matching
at the same location.  So the following is always going to be false:</p>
<pre>    / . &amp; .. /</pre>
<p>It would be possible to have the other semantics where, as long as
the trailing assertion matches either way, it doesn't have to match
the trailing assertion the <i>same</i> way.  But then tell me whether <code>$1</code>
should return &quot;<code>O</code>&quot; or &quot;<code>G</code>&quot; after this:</p>
<pre>    &quot;DOG&quot; ~~ /^[. &amp; ..] (.)/</pre>
<p>Besides, it's easy enough to get the other semantics with lookahead
assertions.  Autoanchoring all the legs of a conjunction to the same
spot adds much more value to it by differentiating it from lookahead.
You have to work pretty hard to make separate lookaheads match the
same length.  Plus doing that turns what should be a symmetric
operator into a non-symmetrical one, where the final lookahead
can't be a lookahead because someone has to &quot;eat&quot; the characters
that all the assertions have agreed on are the right number to eat.
So for all these reasons it's better to have a conjunction operator
with complicated enough start/stop semantics to be useful.</p>
<p>Actually, this operator was originally suggested to me by a biologist.
Which leads us to our...</p>
<a name='Optional Mandatory Cross-disciplinary Joke for People Tired of Dogs'></a><h1>Optional Mandatory Cross-disciplinary Joke for People Tired of Dogs</h1>
<pre>    Biologist: What's worse than being chased by a Velociraptor?
    Physicist: Obviously, being chased by an Acceloraptor.</pre>
<a name='Future Directions'></a><h1>Future Directions</h1>
<p>Away from Acceloraptors, obviously.</p>
<a name='References...er, Reference...'></a><h1>References...er, Reference...</h1>
<pre>  Nathanael Schärli, Stéphane Ducasse, Oscar Nierstrasz and Andrew
      Black. Traits: Composable Units of Behavior. European Conference on
      Object-Oriented Programming (ECOOP), July 2003. Springer LNCS 2743,
      Ed. Luca Cardelli.</pre>
</div>
